Summary of MyBatis related interview questions

1. What is Mybatis?

  • Mybatis is a semi-ORM (Object Relational Mapping) framework that encapsulates JDBC internally. When developing, you only need to focus on the SQL statement itself, and do not need to spend energy on complex processes such as loading drivers, creating connections, and creating statements. Programmers directly write original SQL, which can strictly control SQL execution performance and provide high flexibility.
  • MyBatis can use XML or annotations to configure and map native information, mapping POJOs into records in the database, avoiding almost all JDBC code and manual setting of parameters and obtaining result sets.
  • The various statements to be executed are configured through xml files or annotations, and the final executed sql statement is generated by mapping the java object and the dynamic parameters of the sql in the statement. Finally, the mybatis framework executes the sql and maps the result into a java object and return. (The process from executing sql to returning result).

2. Advantages of Mybaits

  1. Programming based on SQL statements is quite flexible and will not have any impact on the existing design of the application or database. SQL is written in XML, decoupling SQL from program code and facilitating unified management; XML tags are provided to support writing dynamic SQL statements , and can be reused.
  2. Compared with JDBC, the amount of code is reduced by more than 50%, eliminating a large amount of redundant code in JDBC, and there is no need to manually switch connections;
  3. Very compatible with various databases (because MyBatis uses JDBC to connect to the database, MyBatis supports all databases supported by JDBC).
  4. Ability to integrate well with Spring;
  5. Provides mapping tags to support ORM field relationship mapping between objects and databases; provides object relationship mapping tags to support object relationship component maintenance.

3. Disadvantages of the MyBatis framework

  1. The workload of writing SQL statements is relatively large, especially when there are many fields and related tables, which requires developers to have certain skills in writing 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 flexible enough DAO layer solution.
  2. For projects that have high performance requirements or have changing needs, such as Internet projects, MyBatis will be a good choice.

5. What are the differences between MyBatis and Hibernate?

  1. Mybatis is different from hibernate in that it is not entirely an ORM framework because MyBatis requires programmers to write Sql statements themselves.
  2. Mybatis directly writes original SQL, can strictly control SQL execution performance, and is highly flexible. It is very suitable for software development that does not have high requirements for relational data models, because the requirements of this type of software change frequently, and once the requirements change, the results must be output quickly. However, the premise of flexibility is that mybatis cannot be database independent. If you need to implement software that supports multiple databases, you need to customize multiple sets of sql mapping files, which is a heavy workload.
  3. Hibernate has strong object/relational mapping capabilities and good database independence. For software with high requirements on relational models, if you use hibernate to develop it, you can save a lot of code and improve efficiency.

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

#{} is precompilation processing, ${} is string replacement.

When Mybatis processes #{}, it will replace #{} in sql with ? and call the set method of PreparedStatement to assign value;

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

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

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

  1. By defining the alias of the field name in the SQL statement of the query, 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>
  1. By mapping 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 fuzzy query like statement?

Add sql wildcards in Java code

string wildcardname =%smi%;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like #{
    
    value}
</select>

Splicing wildcard characters into 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 have a Dao interface corresponding to it. How does this Dao interface work? If the method in the Dao interface has different parameters, can the method 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 Mapper's Statement 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 fully qualified name of the interface + the method name are concatenated into a string as the key value, which can uniquely locate a MapperStatement. In Mybatis, each , , and tag will be parsed into a MapperStatement object.

For example: com.mybatis3.mappers.StudentDao.findStudentById, you can uniquely find the MapperStatement whose namespace is com.mybatis3.mappers.StudentDao and whose id is findStudentById.

The methods in the Mapper interface cannot be overloaded because the saving and searching strategy of fully qualified name + method name is used. The working principle of the Mapper interface is JDK dynamic proxy. When Mybatis is running, 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, execute the sql represented by the MapperStatement, and then return the sql execution result.

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

Mybatis uses RowBounds objects for paging, which is memory paging performed for the ResultSet result set, rather than physical paging. You can directly write parameters with physical paging in sql to complete the physical paging function, or you can use a paging plug-in to complete 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 interception method of the plug-in, then rewrite the SQL, and add the corresponding physical paging statements and physical paging parameters according to the dialect dialect.

11. How does Mybatis encapsulate the SQL execution results into target objects and return them? What are the mapping forms?

The first is to use tags to define the mapping relationship between database column names and object attribute names one by one.
The second method is to use the sql column alias function and write the column alias as the object attribute name.

After having the mapping relationship between column names and attribute names, Mybatis creates objects through reflection, and uses reflection to assign values ​​​​one by one to the properties of the object and return them. For those properties that cannot find the mapping relationship, the assignment cannot be completed.

14. How to pass multiple parameters in mapper?

1. Functions of DAO layer

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>

2. Use @param annotation:

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

Then, you can use it in xml as follows (it is recommended to encapsulate it as a map and pass it to 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. 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();
}

22. Does Mybatis support delayed loading? If supported, what is its implementation principle?

Answer: Mybatis only supports lazy loading of association objects and collection objects. Association refers to one-to-one query, 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 a proxy object of the target object. When the target method is called, the interceptor method is entered, such as calling a.getB().getName(). The interceptor invoke() method finds that a.getB() is null value, then the pre-saved sql query associated with the B object will be sent separately, B will be queried, and then a.setB(b) will be called, so the object b attribute of a will have a value, and then a.getB( ).getName() method call. This is the basic principle of lazy loading.

Of course, not only Mybatis, but almost all including Hibernate, the principle of supporting lazy loading is the same.

23. Mybatis’s first-level and second-level cache

1) First-level cache: HashMap local cache based on PerpetualCache, its storage scope is Session. When the Session is flushed or closed, all Cache in the Session will be cleared, and the first-level cache is turned on by default.

2) The second-level cache has the same mechanism as the first-level cache. By default, it also uses PerpetualCache and HashMap storage. The difference is that its storage scope is Mapper (Namespace), and the storage source can be customized, such as Ehcache. The second-level cache is not enabled by default. To enable the second-level cache, using the second-level cache attribute class requires implementing 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 certain scope (first-level cache Session/second-level cache Namespaces) performs a C/U/D operation, the cache in all selects under this scope will be cleared by default.

I have also prepared complete interview materials for 2023 for students~
How to get it: Follow the official account below and reply: Interview

Insert image description here

The article is continuously updated. You can follow the official account below or search "Last Rosemary" on WeChat and reply "Interview" to obtain complete interview information.

Guess you like

Origin blog.csdn.net/qq_38374397/article/details/134996899
Recommended