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的XML映射文件中<trim>元素所有场景下的完整使用示例代码

《在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码》在MyBatis的XML映射文件中,trim元素用于动态添加SQL语句的一部分,处理前缀、后缀及多余的逗号或连接符,示... 在MyBATis的XML映射文件中,<trim>元素用于动态地添加SQL语句的一部分,例如SET或W

Mybatis官方生成器的使用方式

《Mybatis官方生成器的使用方式》本文详细介绍了MyBatisGenerator(MBG)的使用方法,通过实际代码示例展示了如何配置Maven插件来自动化生成MyBatis项目所需的实体类、Map... 目录1. MyBATis Generator 简介2. MyBatis Generator 的功能3

Mybatis提示Tag name expected的问题及解决

《Mybatis提示Tagnameexpected的问题及解决》MyBatis是一个开源的Java持久层框架,用于将Java对象与数据库表进行映射,它提供了一种简单、灵活的方式来访问数据库,同时也... 目录概念说明MyBATis特点发现问题解决问题第一种方式第二种方式问题总结概念说明MyBatis(原名

SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码

《SpringBoot基于MyBatis-Plus实现LambdaQuery查询的示例代码》MyBatis-Plus是MyBatis的增强工具,简化了数据库操作,并提高了开发效率,它提供了多种查询方... 目录引言基础环境配置依赖配置(Maven)application.yml 配置表结构设计demo_st

解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题

《解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题》本文主要讲述了在使用MyBatis和MyBatis-Plus时遇到的绑定异常... 目录myBATis-plus-boot-starpythonter与mybatis-spring-b

Spring Boot 中整合 MyBatis-Plus详细步骤(最新推荐)

《SpringBoot中整合MyBatis-Plus详细步骤(最新推荐)》本文详细介绍了如何在SpringBoot项目中整合MyBatis-Plus,包括整合步骤、基本CRUD操作、分页查询、批... 目录一、整合步骤1. 创建 Spring Boot 项目2. 配置项目依赖3. 配置数据源4. 创建实体类

Mybatis拦截器如何实现数据权限过滤

《Mybatis拦截器如何实现数据权限过滤》本文介绍了MyBatis拦截器的使用,通过实现Interceptor接口对SQL进行处理,实现数据权限过滤功能,通过在本地线程变量中存储数据权限相关信息,并... 目录背景基础知识MyBATis 拦截器介绍代码实战总结背景现在的项目负责人去年年底离职,导致前期规

MyBatis框架实现一个简单的数据查询操作

《MyBatis框架实现一个简单的数据查询操作》本文介绍了MyBatis框架下进行数据查询操作的详细步骤,括创建实体类、编写SQL标签、配置Mapper、开启驼峰命名映射以及执行SQL语句等,感兴趣的... 基于在前面几章我们已经学习了对MyBATis进行环境配置,并利用SqlSessionFactory核

MyBatis延迟加载的处理方案

《MyBatis延迟加载的处理方案》MyBatis支持延迟加载(LazyLoading),允许在需要数据时才从数据库加载,而不是在查询结果第一次返回时就立即加载所有数据,延迟加载的核心思想是,将关联对... 目录MyBATis如何处理延迟加载?延迟加载的原理1. 开启延迟加载2. 延迟加载的配置2.1 使用

mybatis的整体架构

mybatis的整体架构分为三层: 1.基础支持层 该层包括:数据源模块、事务管理模块、缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块、解析器模块 2.核心处理层 该层包括:配置解析、参数映射、SQL解析、SQL执行、结果集映射、插件 3.接口层 该层包括:SqlSession 基础支持层 该层保护mybatis的基础模块,它们为核心处理层提供了良好的支撑。