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

Spring+MyBatis+jeasyui 功能树列表

java代码@EnablePaging@RequestMapping(value = "/queryFunctionList.html")@ResponseBodypublic Map<String, Object> queryFunctionList() {String parentId = "";List<FunctionDisplay> tables = query(parent

Mybatis中的like查询

<if test="templateName != null and templateName != ''">AND template_name LIKE CONCAT('%',#{templateName,jdbcType=VARCHAR},'%')</if>

JavaWeb【day09】--(Mybatis)

1. Mybatis基础操作 学习完mybatis入门后,我们继续学习mybatis基础操作。 1.1 需求 需求说明: 根据资料中提供的《tlias智能学习辅助系统》页面原型及需求,完成员工管理的需求开发。 通过分析以上的页面原型和需求,我们确定了功能列表: 查询 根据主键ID查询 条件查询 新增 更新 删除 根据主键ID删除 根据主键ID批量删除

MyBatis 切换不同的类型数据库方案

下属案例例当前结合SpringBoot 配置进行讲解。 背景: 实现一个工程里面在部署阶段支持切换不同类型数据库支持。 方案一 数据源配置 关键代码(是什么数据库,该怎么配就怎么配) spring:datasource:name: test# 使用druid数据源type: com.alibaba.druid.pool.DruidDataSource# @需要修改 数据库连接及驱动u

mybatis框架基础以及自定义插件开发

文章目录 框架概览框架预览MyBatis框架的核心组件MyBatis框架的工作原理MyBatis框架的配置MyBatis框架的最佳实践 自定义插件开发1. 添加依赖2. 创建插件类3. 配置插件4. 启动类中注册插件5. 测试插件 参考文献 框架概览 MyBatis是一个优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射,为开发者提供了极大的灵活性和便利性。以下是关于M

mybatis if test 之 0当做参数传入出问题

首先前端传入了参数 if(StringUtils.isNotBlank(status)){requestParam.setProperty("status", Integer.parseInt(status));}List<SuperPojo> applicationList = groupDao.getApplicationListByReviewStatusAndMember(req

滚雪球学MyBatis(02):环境搭建

环境搭建 前言 欢迎回到我们的MyBatis系列教程。在上一期中,我们详细介绍了MyBatis的基本概念、特点以及它与其他ORM框架的对比。通过这些内容,大家应该对MyBatis有了初步的了解。今天,我们将从理论走向实践,开始搭建MyBatis的开发环境。了解并掌握环境搭建是使用MyBatis的第一步,也是至关重要的一步。 环境搭建步骤 在开始之前,我们需要准备一些必要的工具和软件,包括J

利用Mybatis-generator工具自动生成代码

配置JAVA环境变量; 执行生成代码之前,我们须要做的准备工作。  1、新建一个文件夹,作为我们的工作空间,例如:  D:\generator  注意:这里的路径不要带有中文字符,这是规范,即使带有中文字符不会出什么问题。  2、在 generator 这路径下  (1)放置 mybatis-generator-core-1.3.2.jar;  (2)放置 mysql-connector-ja

MyBatis学习——解决字段名与实体类属性名不相同的冲突

转载地址:http://www.cnblogs.com/xdp-gacl/p/4264425.html