25 most common MyBatis interview questions

Welcome to follow
CSDN: programmer lamb
WeChat public account: programmer lamb

1. What is Mybatis?

  1. Mybatis is a semi-ORM (Object Relational Mapping) framework, which encapsulates JDBC internally. You only need to pay attention to the SQL statement itself during development, and you don't need to spend energy to deal with complicated processes such as loading drivers, creating connections, and creating statements. The programmer directly writes the original ecological SQL, which can strictly control the SQL execution performance and has high flexibility.
  2. MyBatis can use XML or annotations to configure and map native information, and map POJOs to records in the database, avoiding almost all JDBC codes and manual setting of parameters and obtaining result sets. 3. Configure the various statements to be executed through xml files or annotations, and generate the final executed SQL statements through the java object and the dynamic parameters of sql in the statement. Finally, the mybatis framework executes sql and maps the results to java Object and return. (The process from executing sql to returning result).

2. The advantages of Mybaits

  1. Based on SQL statement programming, it is quite flexible and will not have any impact on the existing design of the application or database. SQL is written in XML, which decouples sql and program code and facilitates unified management; XML tags are provided to support the writing of dynamic SQL statements , And can be reused.
  2. Compared with JDBC, it reduces the amount of code by more than 50%, eliminates a large amount of redundant code in JDBC, and does not require manual switch connections;
  3. It is very compatible with various databases (because MyBatis uses JDBC to connect to the database, so as long as the database supported by JDBC is supported by MyBatis).
  4. Able to integrate well with Spring;
  5. Provide mapping tags to support ORM field relationship mapping between objects and databases; provide object-relational mapping tags to support object-relational component maintenance.

3. Disadvantages of MyBatis framework

  1. The workload of writing SQL statements is relatively large, especially when there are many fields and associated tables, there are certain requirements for developers to write SQL statements.
  2. SQL statements depend on the database, resulting in poor database portability, and the database cannot be replaced at will.

4. Applicable occasions of MyBatis framework

  1. MyBatis focuses on SQL itself and is a sufficiently flexible DAO layer solution.
  2. For projects that have high performance requirements or changes in demand, such as Internet projects, MyBatis will be a good choice.

5. What is the difference between MyBatis and Hibernate?

  1. Mybatis is different from hibernate in that it is not exactly an ORM framework, because MyBatis requires programmers to write Sql statements.
  2. Mybatis directly writes original ecological SQL, which can strictly control SQL execution performance and has high flexibility. It is very suitable for software development that does not require high requirements for relational data models, because such software requirements change frequently, and once demand changes require rapid output. But the premise of flexibility is that mybatis cannot achieve database independence. If you need to implement software that supports multiple databases, you need to customize multiple sets of sql mapping files, which is a lot of work.
  3. Hibernate has strong object/relational mapping capabilities and good database independence. For software with high requirements for relational models, if you develop with hibernate, you can save a lot of code and improve efficiency.

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

#{} is pre-compilation processing, KaTeX parse error: Expected'EOF', got'#' at position 22: …replacement. When Mybatis processes #̲{} , it replaces ${} with the value of the variable when #{... {} in sql is used.
Using #{} can effectively prevent SQL injection and improve system security

7. What should I do when the attribute name in the entity class is different from the field name in the table?

Type 1: By defining the alias of the field name in the query sql statement, the alias of the field name is consistent with the attribute name of the entity class.

<select id=”selectorder” parametertype=”int” resultetype= me.gacl.domain.order”>
select order_id id, order_no orderno ,order_price price form orders where order_id=#{id};
</select>

Type 2: Through to map the one-to-one correspondence between field names and entity class attribute names.


<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>

8. How to write like statement in fuzzy query?

Type 1: Add sql wildcard in Java code.


string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);


<select id=”selectlike”>
	select * from foo where bar like #{value}
</select>

Type 2: Splicing wildcards in sql statements will cause sql injection

String wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);

<select id=”selectlike”>
	select * from foo where bar like "%"#{value}"%"
</select>

9. Usually an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of this 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 fully qualified name of the interface is the value of the namespace in the mapping file;
the method name of the interface is the id value of the Statement of the Mapper in the mapping file;
the parameters in the interface method are the parameters passed to sql.
The Mapper interface does not have an implementation class. When calling an interface method, the interface full name + method name splicing character
string as the key value can uniquely locate a MapperStatement. In Mybatis, each
tag,, and tag will be parsed as a
MapperStatement object.

For example: com.mybatis3.mappers.StudentDao.findStudentById, the
only MapperStatement whose namespace is com.mybatis3.mappers.StudentDao and whose id is findStudentById can be found.

The methods in the Mapper interface cannot be overloaded, because the storage and search
strategy of fully qualified name + method name is used . The working principle of the Mapper interface is the JDK dynamic proxy. When Mybatis runs, it will use the JDK
dynamic proxy to generate a proxy object proxy for the Mapper interface. The proxy object will intercept the interface method and execute the sql represented by the MapperStatement instead, and then return the sql execution result.

10.How to get the automatically generated (primary) key value?

The insert method always returns an int value, which represents the number of rows inserted.
If the self-growth strategy is adopted, the automatically generated key value can be set to the passed parameter object after the insert method is executed.
Example:

<insert id=”insertname” usegeneratedkeys=”true” keyproperty=”id”> 
	insert into names (name) values (#{name})
</insert>
name name = new name(); name.setname(“fred”);
int rows = mapper.insertname(name);
// 完成后,id 已经被设置到对象中
system.out.println(“rows inserted =+ rows); 
system.out.println(“generated key value =+ name.getid());

11. How to pass multiple parameters in mapper?

1. The first type:
DAO layer function

public UserselectUser(String name,String area);

Corresponding xml, #{0} represents the first parameter in the dao layer is received, #{1} represents the second parameter in the dao layer, more parameters can be added later.

<select id="selectUser"resultMap="BaseResultMap">
	select * fromuser_user_t whereuser_name = #{0} anduser_area=#{1}
</select>

2. The second: use @param annotation

public interface usermapper {
    
    
	user selectuser(@param(“username”) string username,@param(“hashedpassword”) string hashedpassword);
}

Then, it can be used in xml like the following (recommended to be packaged as a map, passed to the mapper as a single parameter

<select id=”selectuser” resulttype=”user”>
select id, username, hashedpassword from some_table where username = #{username}
and hashedpassword = #{hashedpassword}
</select>

3. 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();
}

12. 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 based on 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.

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

Answer: ,,,,, plus 9 tags for dynamic sql, among which are sql fragment tags, introduce sql fragments through tags, and generate strategy tags for primary keys that do not support auto-increment.

14. 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, then the id cannot be repeated; the
reason is that namespace+id is used as the key of Map<String, MapperStatement>, if there is no namespace, there will be Under the id, then duplicate id will cause data to overwrite each other. With a namespace, id can be repeated naturally, and namespace+id is naturally different if the namespace is different.

15. Why is Mybatis a semi-automatic ORM mapping tool? What is the difference between it and fully automatic?

Hibernate is a fully automatic ORM mapping tool. When you use Hibernate to query related objects or related collection objects, you can directly obtain them according to the object relationship model, so it is fully automated. When Mybatis queries related objects or related collection objects, you need to manually write sql to complete, so it is called a semi-automatic ORM mapping tool.

16. One-to-one and one-to-many related queries?

	<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>

17. How many ways does MyBatis implement one-to-one? How do you do it?

There are joint query and nested query. Joint query is a joint query of several tables, which can be queried only once. It can be completed by configuring the association node in the resultMap to configure a one-to-one class;
nested query is to check a table first, according to this table The foreign key id of the result in it, to query data in another table, is also configured through association, but the query of another table is configured through the select attribute

18. There are several ways to realize one-to-many in MyBatis, how to operate?

There are joint queries and nested queries. A joint query is a joint query of several tables, which is only queried once, and can be completed by configuring a one-to-many class in the collection node in the resultMap; a nested query is to check a table first, according to the foreign key id of the result in the table, To query data in another table is also configured through collection, but query of another table is configured through select node.

19. Does Mybatis support lazy loading? If so, what is its implementation principle?

Answer: Mybatis only supports lazy loading of association objects and collection objects. Association refers to one-to-one, and collection refers to one-to-many query. In the Mybatis configuration file, you can configure whether to enable lazy loading lazyLoadingEnabled=true|false.
Its principle is to use CGLIB to create the proxy object of the target object. When the target method is called, enter the interceptor method, such as calling a.getB().getName(), the interceptor invoke() method finds that a.getB() is null value, then it will separately send the previously saved sql query associated with the B object, query B up, and then call a.setB(b), so the object b attribute of a has a value, and then complete a.getB( ).getName()
method call. This is the basic principle of lazy loading.
Of course, not only Mybatis, but almost all, including Hibernate, support the principle of lazy loading.

20, Mybatis's primary and secondary cache

  1. Level 1 cache: HashMap local cache based on PerpetualCache. Its storage scope is Session. After Session flush or close, all Caches in the Session will be emptied, and Level 1 cache is turned on by default.
  2. The mechanism of the second-level cache is the same as that of the first-level cache. PerpetualCache and HashMap storage are also used by default. The difference is that the storage scope is Mapper (Namespace), and the storage source can be customized, such as Ehcache. The second-level cache is not turned on by default. To enable the second-level cache, the use of the second-level cache attribute class needs to implement the Serializable serialization interface (which can be used to save the state of the object), which can be configured in its mapping file;
  3. 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.

21. 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 methods provided by SqlSession .
There are two ways to implement interface binding. One is to bind via annotations, which 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.

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

  1. The method name of the Mapper interface is the same as the id of each SQL defined in mapper.xml;
  2. The input parameter type of the Mapper interface method is the same as the parameterType of each SQL defined in mapper.xml;
  3. The output parameter type of the Mapper interface method is the same as the resultType of each SQL defined in mapper.xml;
  4. The namespace in the Mapper.xml file is the classpath of the mapper interface.

23. What are the several 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.
1. Configure the location of mapper.xml in sqlMapConfig.xml

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

2. Define the mapper interface.
3. Implement class integration. SqlSessionDaoSupport mapper method can be used in this.getSqlSession() for data addition, deletion, and modification.
4. Spring configuration

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

The second method: use org.mybatis.spring.mapper.MapperFactoryBean:
1. 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>

2. Define the mapper interface:

  1. The namespace in mapper.xml is the address of the mapper interface
  2. The method name in the mapper interface is consistent with the id of the statement defined in mapper.xml
  3. 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:

  1. Write the mapper.xml file:
    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 consistent, No need to configure in sqlMapConfig.xml.
  2. Define the mapper interface:
    note that the file name of mapper.xml is consistent with the interface name of mapper and is placed in the same directory
  3. Configure the mapper scanner:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<property name="basePackage" value="mapper 接口包地址"></property>
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
  1. After using the scanner, obtain the mapper implementation object from the spring container.

24. 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. Every time 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 to intercept 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.

25. How many ways does MyBatis implement one-to-one? How do you do it?

There are joint query and nested query. The joint query is a joint query of several tables, which can be queried only once. It can be completed by configuring the association node in the resultMap to configure a one-to-one class;
nested query is to check a table first, according to this table The foreign key id of the result inside, to query data in another table, is also configured through association, but the query of another table is configured through the select attribute

Extended connection: click here for more bold styles

The blogger's public account programmer Xiaoyang only posts interview-related tweets
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44395707/article/details/106328597