Mybatis common interview questions (transfer)

Mybatis technology insider series blog, from the perspective of principle and source code, introduces its internal implementation details, whether it is written well or not, I really wrote it with my heart, because it is not an article on how to use Mybatis, so some parameters use The details are omitted, our goal is to introduce the technical architecture and important components of Mybatis, as well as the basic operating principles.

It is very hard to write a blog, but it is not necessarily good to write. The so-called start is very exciting, the process is very painful, and the end is regrettable. The requirements are not high, as long as readers can learn a little technical point that other blogs do not have from the series of blogs, as an author, I am very pleased. I also read blogs written by others, and usually I am very interested in the technology I am currently researching. helpful.

Although there is still a lot of content to write, I think it is pointless to write any more. Any other small function points are operated under the basic framework and basic principles that have been introduced. Only after the end can there be a new beginning. . I have also accumulated some experience in blogging. It feels like copying and pasting with more source code. If there is less source code, I think it’s empty talk. I will write a blog in the future. I hope I can write another blog series on the principle of open source distributed framework.

Come here if you have the guts, I will give a few Mybatis interview questions and see how many you can answer (all of them are from me, not from the Internet).

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

Note: This question was asked by the interviewer to interview my colleague.

Answer: ${} is a variable placeholder in the Properties file. It can be used for tag attribute values ​​and inside SQL. It is a static text replacement. For example, ${driver} will be statically replaced with com.mysql.jdbc.Driver. #{} is the parameter placeholder of sql. Mybatis will replace #{} in sql with a ? sign. Before sql is executed, it will use the parameter setting method of PreparedStatement to set the parameter value for the ? sign placeholder of sql in sequence. , such as ps.setInt(0, parameterValue), the value of #{item.name} is to use reflection to obtain the name attribute value of the item object from the parameter object, which is equivalent to param.getItem().getName().

2. In addition to the common select|insert|updae|delete tags, what other tags are there in the Xml mapping file?

Note: This question was asked by the JD interviewer when he was interviewing me.

Answer: There are many other tags, <resultMap>, <parameterMap>, <sql>, <include>, <selectKey>, plus 9 tags of dynamic sql, trim|where|set|foreach|if|choose| when|otherwise|bind, etc., where <sql> is the sql fragment tag, and the sql fragment is introduced through the <include> tag, and <selectKey> generates a strategy tag for the primary key that does not support auto-increment.

3. In the best practice, usually an Xml mapping file will write a Dao interface corresponding to it. Excuse me, what is the working principle of this Dao interface? Can the method in the Dao interface be overloaded when the parameters are different?

Note: This question was also asked by the JD interviewer when he interviewed me.

Answer: The Dao interface is the Mapper interface that people often say. The full name of the interface is the namespace value in the mapping file, the method name of the interface is the id value of MappedStatement in the mapping file, and the parameters in the interface method are passed. Parameters to sql. The Mapper interface has no implementation class. When calling an interface method, the full interface name + method name concatenated string is used as the key value to uniquely locate a MappedStatement. For example: com.mybatis3.mappers.StudentDao.findStudentById, the namespace can be uniquely found MappedStatement with id = findStudentById under com.mybatis3.mappers.StudentDao. In Mybatis, each <select>, <insert>, <update>, <delete> tag will be parsed as a MappedStatement object.

The method in the Dao interface cannot be overloaded, because it is the saving and searching strategy of the full name + method name.

The working principle of the Dao interface is the JDK dynamic proxy. Mybatis will use the JDK dynamic proxy to generate a proxy proxy object for the Dao interface during runtime. The proxy object proxy will intercept the interface method, execute the sql represented by the MappedStatement, and then return the sql execution result.

4. How does Mybatis perform paging? What is the principle of the paging plugin?

Note: I made it.

Answer: Mybatis uses the RowBounds object for paging, which 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 custom plug-in, intercept the sql to be executed in the plug-in interception method, then rewrite the sql, and add the corresponding physical paging statement and physical paging parameters according to the dialect dialect.

For example: select * from student, after intercepting sql, rewrite it as: select t.* from (select * from student) t limit

0, 10 5. Briefly describe the working principle of Mybatis plug-in and how to write a plug-in.

Note: I made it.

Answer: Mybatis can only write plug-ins for the four interfaces of ParameterHandler, ResultSetHandler, StatementHandler, and Executor. Mybatis uses the dynamic proxy of JDK to generate proxy objects for the interfaces that need to be intercepted to realize the interface method interception function. Whenever these four interfaces are executed Object method, it will enter the interception method, specifically the invoke() method of InvocationHandler. Of course, only those methods you specify to be intercepted will be intercepted.

Implement the Interceptor interface of Mybatis and override the intercept() method, and then write annotations to 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.

6. When Mybatis performs batch insertion, can it return the list of database primary keys?

Note: I made it.

A: Yes, JDBC can, of course Mybatis can.

7. What does Mybatis dynamic sql do? What dynamic sql are there? Can you briefly describe the implementation principle of dynamic sql?

Note: I made it.

Answer: 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 9 dynamic sql tags trim|where|set|foreach|if| choose|when|otherwise|bind.

Its execution principle is to use OGNL to calculate the value of the expression from the sql parameter object, and dynamically splicing sql according to the value of the expression, so as to complete the function of dynamic sql.

8. How does Mybatis encapsulate the sql execution result as a target object and return it? What are the mapping forms?

Note: I made it.

Answer: The first is to use the <resultMap> tag 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, Intelligently find the corresponding object attribute name, you can even write T_NAME AS NaMe, Mybatis can work normally.

With the mapping relationship between column names and attribute names, Mybatis creates objects through reflection, and uses reflection to assign and return the attributes of the object one by one. Those attributes that cannot find the mapping relationship cannot complete the assignment.

9. Can Mybatis perform one-to-one and one-to-many associated queries? What are the implementations, and the differences between them.

Note: I made it.

Answer: Yes, Mybatis can not only perform one-to-one, one-to-many associated queries, but also many-to-one, many-to-many associated queries, and many-to-one queries, which are actually one-to-one queries. ) can be changed to selectList(); a many-to-many query is actually a one-to-many query, just change selectOne() to selectList().

There are two ways to implement related object query. One is to send a separate SQL to query the related object, assign it to the main object, and then return the main object. The other is to use nested query. The meaning of nested query is to use join query. Some of the columns are the attribute values ​​of the A object, and the other part of the columns are the attribute values ​​of the associated object B. The advantage is that only one sql query can be sent. The main object and its associated objects are checked out.

So here comes the question, 100 records from join query, how to determine that there are 5 main objects instead of 100? The principle of deduplication is that the <id> sub-tag in the <resultMap> tag specifies the id column that uniquely determines a record. Mybatis completes the deduplication function of 100 records according to the value of the <id> column. <id> can have Multiple, representing the semantics of a joint primary key.

Similarly, the associated objects of the main object are also repeated according to this principle, although in general, only the main object will have duplicate records, and the associated objects will generally not be duplicated.

For example: the following join query results in 6 records. The first and second columns are the Teacher object columns, and the third column is the Student object column. After Mybatis de-duplicates processing, the result is 1 teacher and 6 students instead of 6 teachers and 6 students. .

       t_id t_name s_id

| 1 | teacher | 38 |
| 1 | teacher | 39 |
| 1 | teacher | 40 |
| 1 | teacher | 41 |
| 1 | teacher | 42 |
| 1 | teacher | 43 |

10. Does Mybatis support lazy loading? If supported, what is its implementation principle?

Note: I made it.

A: Mybatis only supports lazy loading of association-related objects and collection-related 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 a proxy object of the target object. When calling the target method, enter the interceptor method, such as calling a.getB().getName(), the interceptor invoke() method finds that a.getB() is If the value is null, then the sql of the pre-saved 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 property of a will have 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 of them, including Hibernate, support the same principle of lazy loading.

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

Note: I made it.

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 repeated; after all, the namespace is not necessary, it is just a best practice.

The reason is that namespace+id is used as the key of Map<String, MappedStatement>. If there is no namespace, there will be id left, and duplication of id will cause data to overlap each other. With the namespace, the natural id can be repeated. If the namespace is different, the namespace+id will naturally be different.

12. How to perform batch processing in Mybatis?

Note: I made it.

A: Use BatchExecutor to complete batch processing.

13. What Executors does Mybatis have? What is the difference between them?

Note: My

answer : Mybatis has three basic Executor executors, SimpleExecutor, ReuseExecutor, BatchExecutor.

SimpleExecutor: Every time an update or select is executed, a Statement object is opened, and the Statement object is closed immediately after use.

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 it is used up, the Statement object is not closed, but is placed in Map<String, Statement> for the next use. In short, re-use Statement objects.

BatchExecutor: execute update (no select, JDBC batch does not support select), add all sql to the batch (addBatch()), wait for unified execution (executeBatch()), it caches multiple Statement objects, each After the Statement objects are all addBatch() completed, wait for the executeBatch() batches to be executed one by one. Same as JDBC batching.

Scope of action: These features of Executor are strictly limited to the scope of the SqlSession life cycle.

14. How to specify which Executor to use in Mybatis?

Note: I made

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

15. Can Mybatis map the Enum enumeration class?

Note: My

answer : Mybatis can map enumeration classes, not only enumeration classes, Mybatis can map any object to a column of a table. The mapping method is to customize a TypeHandler and implement the setParameter() and getResult() interface methods of 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 the two methods setParameter() and getResult(), which represent setting sql question mark placeholder parameters and getting columns respectively. search result.

16. 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 in front of the A tag?

Note: My

answer : Although Mybatis parses the Xml mapping file in order, the referenced B tag can still be defined anywhere, and Mybatis can correctly identify it.

The principle is that Mybatis parses the A tag and finds that the A tag refers to the B tag, but the B tag has not been parsed and does not exist yet. At this time, Mybatis will mark the A tag as unparsed, and then continue to parse the remaining tags, including B Tags, when all tags are parsed, Mybatis will re-parse those tags that are marked as unparsed. At this time, when the A tag is parsed again, the B tag already exists, and the A tag can be parsed normally.

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

Note: My

answer : Mybatis encapsulates all Xml configuration information into the All-In-One heavyweight object Configuration. In the Xml mapping file, the <parameterMap> tag will be parsed as a ParameterMap object, and each of its child elements will be parsed as a ParameterMapping object. The <resultMap> tag will be parsed as a ResultMap object, and each of its child elements will be parsed as a ResultMapping object. Each <select>, <insert>, <update>, <delete> tag will be parsed as a MappedStatement object, and the sql in the tag will be parsed as a BoundSql object.

18. Why is Mybatis a semi-automatic ORM mapping tool? How is it different from fully automatic?

Note: My

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

The interview questions seem to be very simple, but if you want to answer them correctly, you must be someone who has studied the source code and in-depth, not someone who can only use it or someone who is very familiar with it. All the above interview questions and their answers involve The content is explained and analyzed in detail in my Mybatis series of blogs.
[/size][/size][/size][/size][/size][/size]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326290078&siteId=291194637