Mybatis Interview Question Summary

2024-05-05 06:12

本文主要是介绍Mybatis Interview Question Summary,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. In best practice, usually an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of the Dao interface? Can the methods in the Dao interface be overloaded when the parameters are different?

Answer: The Dao interface is commonly referred to as 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 MappedStatement in the mapping file, and the parameters in the interface method are the parameters passed to sql. Mapper interface has no implementation class. When calling interface methods, the interface full name+method name concatenated string is used as the key value to uniquely locate a MappedStatement, for example: com. mybatis3. mappers StudentDao.findStudentById, you can find that the only namespace is com.mybatis3.mappers MappedStatement with id=findStudentById under StudentDao. In Mybatis, each,,,tag will be resolved to a MappedStatement object.
The method in the Dao interface cannot be overloaded, because it is the save and search strategy of fully qualified name+method name.
The working principle of the Dao interface is JDK dynamic proxy. Mybatis runtime will use JDK dynamic proxy to generate proxy objects for the Dao interface. The proxy object proxy will intercept the interface method, instead execute the sql represented by MappedStatement, and then return the sql execution results.

2. How does Mybatis paginate? What is the principle of paging plug-ins?

Answer: Mybatis uses the RowBounds object for paging. It is memory paging for the ResultSet result set, not physical paging. You can directly write parameters with physical paging in sql to complete the physical paging function, or you can use the 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 user-defined plug-in, intercept the sql to be executed in the plug-in interception method, then rewrite the sql, and add the corresponding physical paging statements and physical paging parameters according to the dialect of dialect.
For example: select * from student. After intercepting sql, it is rewritten as: select t. * from (select * from student) t limit 0, 10

3. 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 four interfaces: ParameterHandler, ResultSetHandler, StatementHandler, and Executor. Mybatis uses the JDK’s dynamic proxy to generate proxy objects for the interfaces that need to be intercepted to implement the interface method interception function. Each time the methods of the four interface objects are executed, the interception method will enter, specifically the invoke() method of the InvocationHandler. Of course, only those methods that you specify need to be intercepted will be intercepted.
Implement the Interceptor interface of Mybatis and copy the intercept() method, then write comments for the plug-in to specify which methods of which interface to intercept. Remember, don’t forget to configure the plug-in you wrote in the configuration file.

4. Can Mybatis return the database primary key list when it performs batch insert?

A: Yes, both JDBC and Mybatis can.

5. What does Mybatis dynamic sql do? What are the dynamic sql? Can you briefly describe the execution principle of dynamic sql?

A: Mybatis dynamic sql allows us to write dynamic sql in the form of tags in the Xml mapping file to complete logical judgment and dynamic splicing of sql. Mybatis provides nine dynamic sql tags trim | where | set | foreach | if | choose | when | otherwise | bind.
Its implementation principle is to use OGNL to calculate the value of the expression from the sql parameter object, and dynamically splice sql according to the value of the expression to complete the dynamic sql function.

6. How does Mybatis encapsulate sql execution results as target objects and return them? What are the mapping forms?

Answer: The first is to use thetag to define the mapping relationship between column names and object attribute names one by one. The second is to use the alias function of the sql column to write the column alias as the object attribute name, such as T_NAME AS NAME. The object attribute name is generally name, lowercase, but the column name is not case sensitive. Mybatis will ignore the case of the column name and find the corresponding object attribute name intelligently. You can even write it as T_NAME AS NaMe. Mybatis can work normally as well.
With the mapping relationship between the column name and the attribute name, Mybatis creates objects through reflection. At the same time, it uses the attributes reflected to the object to assign values one by one and return them. The attributes that cannot find the mapping relationship cannot be assigned.

7. Can Mybatis perform one-to-one and one to many association queries? What are the implementation methods and the differences between them.

A: Yes, Mybatis can not only execute one-to-one and one to many association queries, but also execute many to one and many to many association queries. Many to one queries are actually one-to-one queries. Just change selectOne () to selectList (); Many to many queries are actually one to many queries. You just need to change selectOne () to selectList ().
There are two ways to query associated objects. One is to send a separate sql to query the associated object, assign it to the main object, and then return the main object. The other is to use nested queries, which means to use join queries. One column is the attribute value of object A, and the other column is the attribute value of associated object B. The advantage is that only one sql query can be issued to find the main object and its associated object.
Then the problem arises. The join queries 100 records. How can we determine that there are 5 main objects instead of 100? The principle of de duplication is that thesub tag in thetag specifies the id column that uniquely determines a record. Mybatis performs the de duplication function of 100 records according to thecolumn value. There can be multipletags, representing the semantics of the joint primary key.
Similarly, the associated object of the primary object is repeated according to this principle. Although in general, only the primary object will have duplicate records, the associated object will not be repeated.

8. Does Mybatis support delayed loading? If yes, what is its implementation principle?

Answer: Mybatis only supports delayed loading of association associated objects and collection associated collection objects. Association refers to one-to-one queries and collection refers to one to many queries. In the Mybatis configuration file, you can configure whether to enable lazy loading lazyLoadingEnabled=true | false.
Its principle is that CGLIB is used to create the proxy object of the target object. When the target method is called, the interceptor method will enter, for example, a.getB(). getName(). When the interceptor invoke() method finds that a.getB() is null, the interceptor will separately send the pre saved query sql associated with the B object, query B, and then call a.setB (b), so that the object b property of a has a value, and then complete the call of a.getB(). getName() method. This is the basic principle of delayed loading.
Of course, not only Mybatis, but also Hibernate. The principle of supporting delayed loading is the same.

9. In the Xml mapping file of Mybatis, can the IDs of different Xml mapping files be repeated?

Answer: 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 duplicate; After all, namespaces are not necessary, but best practices.
The reason is that namespace+id is used as the key of Map<String, MappedStatement>. If there is no namespace, there is only an id left. If the id is repeated, the data will overwrite each other. With namespace, the natural ID can be repeated. With different namespaces, the namespace+ID will be different.

10. How to perform batch processing in Mybatis?

Answer: Use BatchExecutor to complete batch processing.

11. What Executor actuators does Mybatis have? What is the difference between them?

A: Mybatis has three basic executors, SimpleExecutor, ReuseExecutor, and BatchExecutor.
SimpleExecutor: Every time an update or select is executed, a Statement object will be opened, and the Statement object will be closed as soon as it is used up.
ReuseExecutor: execute update or select, use sql as the key to find the Statement object, use it if it exists, and create it if it does not exist. After use, do not close the Statement object, but place it in Map<String, Statement>for next use. In short, reusing Statement objects.
BatchExecutor: Execute update (no select, JDBC batch processing does not support select), add all sql to batch processing (addBatch()), and wait for unified execution (executeBatch()). It caches multiple Statement objects. After each Statement object is addBatch(), wait for executeBatch() batch processing one by one. Same as JDBC batch processing.
Scope: These features of the Executor are strictly limited to the SqlSession life cycle.

12. How to specify which Executor executor to use in Mybatis?

Answer: In the Mybatis configuration file, you can specify the default ExecutorType actuator type, or manually pass the ExecutorType type parameter to the method of creating a SqlSession in the DefaultSqlSessionFactory.

13. Can Mybatis map Enum enumeration classes?

Answer: Mybatis can map enumeration classes, not only enumeration classes, but also any object to a column of the table. The mapping method is to customize a TypeHandler and implement the setParameter() and getResult() interface methods of the TypeHandler. TypeHandler has two functions: one is to complete the conversion from javaType to jdbcType, and the other is to complete the conversion from jdbcType to javaType, which is reflected in setParameter() and getResult(), which respectively represent the setting of sql question mark placeholder parameters and obtaining column query results.

14. In the Mybatis mapping file, if the A tag references the content of the B tag through include, can the B tag be defined after the A tag, or must it be defined before the A tag?

Answer: Although Mybatis parses the Xml mapping file in order, the referenced B tag can still be defined anywhere, and Mybatis can correctly recognize it.
The principle is that Mybatis parses the A tag and finds that the A tag references the B tag, but the B tag has not yet been resolved, and does not exist. At this time, Mybatis will mark the A tag as unresolved, and then continue to parse the remaining tags, including the B tag. After all tags are parsed, Mybatis will re parse those tags marked as unresolved. At this time, when parsing the A tag, the B tag already exists, and the A tag can be parsed normally.

15. Briefly describe the mapping relationship between the Xml mapping file of Mybatis and the internal data structure of Mybatis?

Answer: Mybatis encapsulates all the Xml configuration information into the All In One heavyweight object Configuration. In the Xml mapping file, thetag will be resolved into a ParameterMap object, and each of its child elements will be resolved into a ParameterMapping object< The resultMap>tag will be resolved into a ResultMap object, and each of its child elements will be resolved into a ResultMapping object. Each,,, andtag will be resolved to a MappedStatement object, and the sql in the tag will be resolved to a BoundSql object.

16. Why is Mybatis a semi-automatic ORM mapping tool? What is the difference between it and full automation?

Answer: Hibernate is a fully automatic ORM mapping tool. When Hibernate is used to query associated objects or associated collection objects, it can be directly obtained according to the object relationship model, so it is fully automatic. When Mybatis queries associated objects or associated collection objects, it needs to write sql manually. Therefore, it is called a semi-automatic ORM mapping tool.

17. What if 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, make the alias of the field name consistent with the attribute name of the entity class
Type 2: map the one-to-one correspondence between field names and entity class attribute names through

18. How to pass multiple parameters in mapper?

First: the idea of using placeholders
Use # {0} in the mapping file, and # {1} represents the number of parameters passed in
Use the @ param annotation: to name parameters
The second is to use the Map set as a parameter to load

19. What does Mybatis dynamic sql do? What are the dynamic sql? Can you briefly describe the execution principle of dynamic sql?

Mybatis dynamic sql allows us to write dynamic sql in the form of tags in the Xml mapping file to complete the functions of logical judgment and dynamic splicing of sql.
Mybatis provides nine dynamic sql tags: trim | where | set | foreach | if | choose | when | otherwise | bind.
Its implementation principle is to use OGNL to calculate the value of the expression from the sql parameter object, and dynamically splice sql according to the value of the expression to complete the dynamic sql function.

20. In the Xml mapping file of Mybatis, can the IDs of different Xml mapping files be repeated?

If namespace is configured, it can be repeated, because our Statement is actually namespace+id
If the namespace is not configured, the same ID will result in overwriting.

21. How can interface binding be implemented?

Interface binding can be implemented in two ways:
One is binding through annotations, that is, adding@ Select@Update Such annotations contain Sql statements to bind
The other is to bind by writing SQL in xml. In this case, the namespace in the xml mapping file must be the full path name of the interface

22. How does Mybatis paginate? What is the principle of paging plug-ins?

Mybatis uses the RowBounds object for paging. It is memory paging for the ResultSet result set instead of physical paging. You can directly write parameters with physical paging in SQL to complete the physical paging function, or you can use paging plug-ins to complete physical paging.

23. The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a user-defined plug-in, intercept the sql to be executed in the plug-in interception method, and then rewrite the sql. According to the dialect of dialect, add the corresponding physical paging statements and physical paging parameters.

For example:
Select * from student. After intercepting sql, it is rewritten as: select t. * from (select * from student) t limit 0, 10

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

Mybatis can only write plug-ins for the four interfaces: ParameterHandler, ResultSetHandler, StatementHandler, and Executor. Mybatis uses the JDK’s dynamic proxy to generate proxy objects for the interfaces that need to be intercepted to implement the interface method interception function. Whenever the methods of the four interface objects are executed, the interception method will enter, specifically the invoke() method of InvocationHandler. Of course, only those methods that you specify need to be intercepted will be intercepted.
Implement the Interceptor interface of Mybatis and copy the intercept() method, then write comments for the plug-in to specify which methods of which interface to intercept. Remember, don’t forget to configure the plug-in you wrote in the configuration file.

这篇关于Mybatis Interview Question Summary的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/960962

相关文章

mybatis映射器配置小结

《mybatis映射器配置小结》本文详解MyBatis映射器配置,重点讲解字段映射的三种解决方案(别名、自动驼峰映射、resultMap),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定... 目录select中字段的映射问题使用SQL语句中的别名功能使用mapUnderscoreToCame

mybatis-plus如何根据任意字段saveOrUpdateBatch

《mybatis-plus如何根据任意字段saveOrUpdateBatch》MyBatisPlussaveOrUpdateBatch默认按主键判断操作类型,若需按其他唯一字段(如agentId、pe... 目录使用场景方法源码方法改造首先在service层定义接口service层接口实现总结使用场景my

MyBatis ParameterHandler的具体使用

《MyBatisParameterHandler的具体使用》本文主要介绍了MyBatisParameterHandler的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录一、概述二、源码1 关键属性2.setParameters3.TypeHandler1.TypeHa

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

MyBatis-Plus 与 Spring Boot 集成原理实战示例

《MyBatis-Plus与SpringBoot集成原理实战示例》MyBatis-Plus通过自动配置与核心组件集成SpringBoot实现零配置,提供分页、逻辑删除等插件化功能,增强MyBa... 目录 一、MyBATis-Plus 简介 二、集成方式(Spring Boot)1. 引入依赖 三、核心机制

MyBatis的xml中字符串类型判空与非字符串类型判空处理方式(最新整理)

《MyBatis的xml中字符串类型判空与非字符串类型判空处理方式(最新整理)》本文给大家介绍MyBatis的xml中字符串类型判空与非字符串类型判空处理方式,本文给大家介绍的非常详细,对大家的学习或... 目录完整 Hutool 写法版本对比优化为什么status变成Long?为什么 price 没事?怎

Mybatis-Plus 3.5.12 分页拦截器消失的问题及快速解决方法

《Mybatis-Plus3.5.12分页拦截器消失的问题及快速解决方法》作为Java开发者,我们都爱用Mybatis-Plus简化CRUD操作,尤其是它的分页功能,几行代码就能搞定复杂的分页查询... 目录一、问题场景:分页拦截器突然 “失踪”二、问题根源:依赖拆分惹的祸三、解决办法:添加扩展依赖四、分页

MyBatis流式查询两种实现方式

《MyBatis流式查询两种实现方式》本文详解MyBatis流式查询,通过ResultHandler和Cursor实现边读边处理,避免内存溢出,ResultHandler逐条回调,Cursor支持迭代... 目录MyBATis 流式查询详解:ResultHandler 与 Cursor1. 什么是流式查询?

mybatis用拦截器实现字段加解密全过程

《mybatis用拦截器实现字段加解密全过程》本文通过自定义注解和MyBatis拦截器实现敏感信息加密,处理Parameter和ResultSet,确保数据库存储安全且查询结果解密可用... 目录前言拦截器的使用总结前言根据公司业务需要,灵活对客户敏感信息进行加解密,这里采用myBATis拦截器进行简单实

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入