Mybatis interview knowledge points, work knowledge points, dry goods sharing (don’t find it, it’s all here)

Interview questions

1. What is mybatis

Mybatis is a semi-ORM (Object Relational Mapping) framework, which encapsulates JDBC internally, and it can define statements in xml and annotations.

2. Talk about mybatis better than jdbc

(1) Mybatis reduces redundant code, jdbc's rs.getString

(2) The SQL statement can be configured to reduce the amount of code writing.

(3) The connection pool is integrated, and jdbc needs to be implemented with connection pools such as druid.

 

3.#{}${}What is the difference between and ?

#{}It is precompilation processing and ${}string replacement.

When Mybatis is processing #{}, it will #{}replace the sql with the? Sign and call the set method of PreparedStatement to assign;

When Mybatis is processing ${}, it ${}replaces with the value of the variable.

Use #{}can effectively prevent SQL injection and improve system security.

4. What should I do if the table field name is different from the entity class attribute name?

(1) You can use the alias select user_id as id in the statement

  (2) You can use resultMap to map the corresponding relationship.

<select id="getOrder" parameterType="int" resultMap="orderresultmap">  
        select * from orders where order_id=#{id}  
    </select>  
  
   <resultMap type=”me.gacl.domain.order” id=”orderresultmap”>  
        <!–用id属性来映射主键字段–>  
        <id property=”id” column=”order_id”>  
  
        <!–用result属性来映射非主键字段,property为实体类属性名,column为数据表中的属性–>  
        <result property = “orderno” column =”order_no”/>  
        <result property=”price” column=”order_price” />  
    </reslutMap> 

5. How to write a fuzzy query like statement?

Use oracle's || double vertical line to connect the string %, indirectly pre-compiled string.

<select id="select3" resultMap="myMap">

        select * from student where  name like '%' || #{name} || '%'

</select>

Another direct #{value} is not recommended

6. What is the working principle of the Dao interface? When the parameters of the methods in the Dao interface are different, can the methods be overloaded?

The Dao interface is the Mapper interface. The namespace in xml maps the dao interface path, the method name of the interface maps the id attribute of each statement tag in xml, and the parameters in the interface method are the parameters passed to sql.

In Mybatis, each of <select>, <insert>, <update>, <delete>tag, is resolved to a MapperStatement object.

The method cannot be overloaded, because mybatis uses the interface name + method name as the only key to find the statement tag in the xml. The statement tag is stored in the MapperStatement, and the only key-MapperStatement

The working principle of the Mapper interface is the JDK dynamic proxy. Mybatis will use the JDK dynamic proxy to generate the proxy object MapperProxy for the Mapper interface when Mybatis runs. The proxy object will intercept the interface method and execute the sql represented by the MapperStatement instead, and then return the sql execution result.

7. In the Xml mapping file of Mybatis, can the id be repeated for different Xml mapping files?

For different Xml mapping files, if the namespace is configured, the id can be repeated; if the namespace is not configured, the id cannot be repeated;

8. How does Mybatis perform paging? What is the principle of the paging plug-in?

Mybatis uses the RowBounds object for paging, which is memory paging for the ResultSet result set, not physical paging. You can write the parameters with physical paging directly in sql to complete the physical paging function, or you can use the paging plug-in to complete the physical paging.

The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in, intercept the SQL to be executed in the plug-in's interception method, and then rewrite the SQL, according to the dialect dialect, add the corresponding physical paging statement and physical paging parameters.

9. How does Mybatis encapsulate the sql execution result as a target object and return it? What are the mapping forms?

The first is to use <resultMap>tags to define the mapping relationship between database column names and object attribute names one by one.

The second is to use the alias function of the sql column to write the alias of the column as the object attribute name.

With the mapping relationship between column names and attribute names, Mybatis creates objects through reflection, and uses the attributes reflected to the objects to assign and return one by one. Those attributes that cannot find the mapping relationship cannot be assigned.

The third type, automatic hump configuration:

        <setting name="mapUnderscoreToCamelCase" value="true"/>

10.How to pass multiple parameters in mapper?

The first:

// DAO层的函数  
Public UserselectUser(String name,String area);  
// 对应的xml,#{0}代表接收的是dao层中的第一个参数,#{1}代表dao层中第二参数,更多参数一致往后加即可。  
<select id="selectUser"resultMap="BaseResultMap">    
  select *  fromuser_user_t whereuser_name = #{0} anduser_area=#{1}     
</select> 

The second: use @param annotation:

public interface usermapper {  
   user selectuser(@param(“username”) string username,@param(“hashedpassword”) string hashedpassword);  
 }  
// 然后,就可以在xml像下面这样使用(推荐封装为一个map,作为单个参数传递给mapper):  
<select id=”selectuser” resulttype=”user”>  
         select id, username, hashedpassword  
         from some_table  
         where username = #{username} and hashedpassword = #{hashedpassword}   
</select>  

The third type: multiple parameters are encapsulated into a map

try{  
//映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL  
//由于我们的参数超过了两个,而方法中只有一个Object参数收集,因此我们使用Map集合来装载我们的参数  
  Map<String, Object> map = new HashMap();       
  map.put("start", start);       
  map.put("end", end);       
  return sqlSession.selectList("StudentID.pagination", map);   
}catch(Exception e){      
   e.printStackTrace();       
   sqlSession.rollback();      
   throw e; }  
   finally{   
   MybatisUtil.closeSqlSession();   
 }  

 11. What is the use of Mybatis dynamic sql? How does it work? What are the dynamic SQL?

Mybatis dynamic sql can write dynamic sql in the form of tags in the Xml mapping file. The execution principle is to complete the logical judgment according to the value of the expression and dynamically splice the sql function.

Mybatis provides 9 kinds of dynamic sql tags: trim | where | set | foreach | if | choose | when | otherwise | bind.

12. In the Xml mapping file, besides the common select|insert|updae|delete tags, what other tags are there?

<resultMap>, , <parameterMap>, <sql>, <include>, <selectKey>Plus dynamic sql nine labels, wherein the label is a sql fragment, by <include>the label incorporated sql fragment, <selectKey>generating policy tag that does not support the auto-increment primary key.

13. One-to-one, one-to-many related queries?

One-to-one use association, one-to-many use collection

<mapper namespace="com.lcb.mapping.userMapper">    
    <!--association  一对一关联查询 -->    
    <select id="getClass" parameterType="int" resultMap="ClassesResultMap">    
        select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id}    
    </select>    
  
    <resultMap type="com.lcb.user.Classes" id="ClassesResultMap">    
        <!-- 实体类的字段名和数据表的字段名映射 -->    
        <id property="id" column="c_id"/>    
        <result property="name" column="c_name"/>    
        <association property="teacher" javaType="com.lcb.user.Teacher">    
            <id property="id" column="t_id"/>    
            <result property="name" column="t_name"/>    
        </association>    
    </resultMap>    
  
  
    <!--collection  一对多关联查询 -->    
    <select id="getClass2" parameterType="int" resultMap="ClassesResultMap2">    
        select * from class c,teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id}    
    </select>    
  
    <resultMap type="com.lcb.user.Classes" id="ClassesResultMap2">    
        <id property="id" column="c_id"/>    
        <result property="name" column="c_name"/>    
        <association property="teacher" javaType="com.lcb.user.Teacher">    
            <id property="id" column="t_id"/>    
            <result property="name" column="t_name"/>    
        </association>    
  
        <collection property="student" ofType="com.lcb.user.Student">    
            <id property="id" column="s_id"/>    
            <result property="name" column="s_name"/>    
        </collection>    
    </resultMap>    
</mapper>   

14. What is the underlying implementation of Mybatis's primary and secondary caches? How to turn on the second level cache?

The first level cache is a HashMap storage implementation, the scope is sqlsession, and the first level cache is turned on by default.

The secondary cache is also implemented by HashMap. The scope is the namespace level, which is closed by default.

For the cache data update mechanism, when a C/U/D operation is performed in a certain scope (first-level cache Session/second-level cache Namespaces), by default, all the caches in select under this scope will be cleared.

public class MybatisTest {

	public static void main(String[] args) throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession  session = sqlSessionFactory.openSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept dept = mapper.selectByPrimaryKey(10);
		System.out.println(dept);

		DeptMapper mapper1 = session.getMapper(DeptMapper.class);
		Dept dept1 = mapper.selectByPrimaryKey(10);
		System.out.println(dept1);
	}
}

 //一级缓存验证:结果显示 查询语句只打印了一次

Implement the second-level cache:

1. Configure to enable <setting name="cacheEnabled" value="true"/> <!-- Enable secondary cache-->

2. To enable the second-level cache, the POJO object must also implement the Serializable interface, otherwise an exception will be thrown. 

15. What is the interface binding of MyBatis? What are the ways to achieve it?

Interface binding is to define the interface arbitrarily in MyBatis, and then bind the methods in the interface to the SQL statement, we can directly call the interface method, so that we can have more flexible choices and settings than the original method provided by SqlSession .

There are two ways to implement interface binding. One is to bind via annotations, that is, to add @Select, @Update and other annotations to the interface method, which contains Sql statements to bind; the other is to write SQL in xml To bind, in this case, the namespace in the xml mapping file must be the full path name of the interface. When the Sql statement is relatively simple, use annotation binding, when the SQL statement is more complex, use xml binding, generally use xml binding more.

16. What are the requirements when using the mapper interface of MyBatis to call?

The Mapper interface method name is the same as the id of each SQL defined in mapper.xml;

The input parameter type of the Mapper interface method is the same as the parameterType of each SQL defined in mapper.xml;

The output parameter type of the Mapper interface method is the same as the resultType of each SQL defined in mapper.xml;

The namespace in the Mapper.xml file is the classpath of the mapper interface.

17. What are the ways to write Mapper?

The first: the interface implementation class inherits SqlSessionDaoSupport: to use this method, you need to write the mapper interface, the mapper interface implementation class, and the mapper.xml file.

Configure the location of mapper.xml in sqlMapConfig.xml

<mappers>  
    <mapper resource="mapper.xml文件的地址" />  
    <mapper resource="mapper.xml文件的地址" />  
</mappers>  

Define the mapper interface

Implementation class integration SqlSessionDaoSupport

In the mapper method, this.getSqlSession() can be used to add, delete, modify and check data.

spring configuration

<bean id=" " class="mapper接口的实现">  
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
</bean>  

The second: use org.mybatis.spring.mapper.MapperFactoryBean:

Configure the location of mapper.xml in sqlMapConfig.xml. If mapper.xml and mappre interface have the same name and are in the same directory, there is no need to configure

<mappers>  
    <mapper resource="mapper.xml文件的地址" />  
    <mapper resource="mapper.xml文件的地址" />  
</mappers>  

Define the mapper interface:

The namespace in mapper.xml is the address of the mapper interface

The method name in the mapper interface is consistent with the id of the statement defined in mapper.xml

Defined in Spring

<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    <property name="mapperInterface"   value="mapper接口地址" />   
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />   
</bean>  

The third type: use mapper scanner:

The mapper.xml file is written:

  • The namespace in mapper.xml is the address of the mapper interface;

  • The method name in the mapper interface is consistent with the id of the statement defined in mapper.xml;

  • If the names of mapper.xml and mapper interface are kept the same, there is no need to configure them in sqlMapConfig.xml.

  • Note that the file name of mapper.xml is consistent with the interface name of mapper and is placed in the same directory

18. Briefly describe the operation principle of Mybatis plug-in and how to write a plug-in.

Answer: Mybatis can only write plug-ins for the 4 interfaces of ParameterHandler, ResultSetHandler, StatementHandler, and Executor. Mybatis uses the dynamic proxy of the JDK to generate proxy objects for the interfaces that need to be intercepted to implement the interface method interception function, and whenever these 4 interfaces are executed When the method of the object, it will enter the interception method, specifically the invoke() method of the InvocationHandler. Of course, only those methods that you specify that need to be intercepted will be intercepted.

Write a plug-in: implement the Interceptor interface of Mybatis and override the intercept() method, and then write an annotation for the plug-in to specify which methods of which interface you want to intercept. Remember, don't forget to configure the plug-in you wrote in the configuration file.

 

Guess you like

Origin blog.csdn.net/x18094/article/details/115261377