[Latest in October] 25 mybatis interview questions that must be asked, if you can, you can also go to Dachang

table of Contents

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

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

3. In best practice, usually an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of this Dao interface? When the method in Dao interface has different parameters, can the method be overloaded?

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

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

6. Mybatis executes batch insert, can it return the database primary key list?

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

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

9. Can Mybatis perform one-to-one and one-to-many related queries? What are the implementation methods, and the differences between them.

10. Does Mybatis support delayed loading? If so, what is its implementation principle?

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

12. How to execute batch processing in Mybatis?

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

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

15. Can Mybatis map Enum enumeration class?

16. In the Mybatis mapping file, if the A tag refers to 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?

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

18. Why is Mybatis a semi-automatic ORM mapping tool? What is the difference between it and fully automatic?

19. What is Mybatis?

20. Advantages of Mybaits:

21. Disadvantages of MyBatis framework:

22. What are the advantages and disadvantages of the ibatis/mybatis framework?

23. The role of the ibatis core class; the role of the MyBatis core class?

24. Comparison between mybatis/ibatis and hibernate;

25. The working principle of Mybatis:


Mybatis technical insider series of blogs, from the perspective of principle and source code, introduces its internal implementation details, whether it is good or not, I really wrote it carefully, because it is not an article about how to use Mybatis, so some parameters are used The details are omitted. Our goal is to introduce the technical architecture and important components of Mybatis, as well as the basic operating principles.

The blog is very hard to write, but it is not necessarily good-looking. The so-called beginning is very exciting, the process is painful, and the end is regrettable. The requirements are not high. As long as readers can learn a little bit of technical points from the series of blogs that other blogs do not have, as an author, I am very pleased. I also read blogs written by others. Usually, I am very familiar with my current research technology. helpful.

Although there is still a lot of content to write, I think it is meaningless to write it down. Any other small function points are operated under the basic framework and basic principles already introduced. Only when it is over can a new start. . I have also accumulated some experience in blogging. If the source code is too much, it feels like copying and pasting. If the source code is less, I feel that it is an empty talk principle. I will write a blog in the future. I hope it will be a "refined blog post". I hope I can write another blog on the principles of open source distributed framework.

The following are the interview questions shared with everyone, like you can bookmark!

 

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

Answer: It is a variable placeholder in the Properties file. It can be used for label attribute values ​​and inside SQL. It is a static text replacement. For example, it is a variable placeholder in the Properties file. It can be used for label attribute values ​​and inside SQL. It belongs to static text replacement. For example, {driver} will be statically replaced with com.mysql.jdbc.Driver. #{} is a placeholder for sql parameters. Mybatis will replace #{} in sql with a? Number. Before sql is executed, it will use the parameter setting method of PreparedStatement, and set the parameter values ​​to the placeholder for sql? For example, 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 the Xml mapping file, besides the common select|insert|updae|delete tags, what other tags are there?

Note: This question was asked by the JD interviewer during the interview.

Answer: There are many other tags, <resultMap>, <parameterMap>, <sql>, <include>, <selectKey>, plus 9 tags for 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> is the primary key generation strategy tag that does not support auto-increment.

3. In best practice, usually an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of this Dao interface? When the method in Dao interface has different parameters, can the method be overloaded?

Answer: Dao interface is the Mapper interface that people often say. 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 passed Parameters to sql. The Mapper interface does not have an implementation class. When calling the interface method, the interface full name + method name splicing string as the key value can uniquely locate a MappedStatement, for example: com.mybatis3.mappers.StudentDao.findStudentById, the namespace can be uniquely found For com.mybatis3.mappers.StudentDao, the MappedStatement with id = findStudentById below. In Mybatis, every <select>, <insert>, <update>, and <delete> tag will be parsed as a MappedStatement object.

The method in the Dao interface cannot be overloaded, because it is the storage and search strategy of the fully qualified 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 when running. The proxy object proxy will intercept the interface method and execute the SQL represented by the MappedStatement instead, and then return the SQL execution result.

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

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 plugin 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's interception method, and then rewrite the SQL, according to the dialect dialect, add the corresponding physical paging statement and physical paging parameters.

Example: select * from student, after intercepting sql, rewrite as: select t.* from (select * from student) t limit 0,10

5. 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 of ParameterHandler, ResultSetHandler, StatementHandler, and Executor. Mybatis uses the dynamic proxy of the JDK to generate proxy objects for the interfaces that need to be intercepted to implement the interface method interception function. Whenever these four interfaces are executed When the method of the object, it will enter the interception method, specifically the invoke() method of the InvocationHandler. Of course, only those methods that you specify to intercept will be intercepted.

Implement the Interceptor interface of Mybatis and override the intercept() method, and then write an annotation for 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. Mybatis executes batch insert, can it return the database primary key list?

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

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

Answer: Mybatis dynamic sql allows us to write dynamic sql in the form of tags in the Xml mapping file, complete logical judgment and dynamic splicing sql function, Mybatis provides 9 kinds of dynamic sql tags trim|where|set|foreach|if| choose|when|otherwise|bind.

The principle of execution 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 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?

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, and Mybatis can work normally.

With the mapping relationship between column names and attribute names, Mybatis creates objects through reflection, and uses the attributes reflected to the objects to assign and return one by one. Those attributes that cannot find the mapping relationship cannot be assigned.

9. Can Mybatis perform one-to-one and one-to-many related queries? What are the implementation methods, and the differences between them.

Answer: Yes, Mybatis can not only perform one-to-one, one-to-many related queries, but also perform many-to-one, many-to-many related queries, many-to-one queries, which are actually one-to-one queries. You only need to put selectOne( ) Can be modified to selectList(); a many-to-many query is actually a one-to-many query, just change selectOne() to selectList().

Related object query, there are two ways to achieve, one is to send a separate SQL to query the associated object, assign it to the main object, and then return to the main object. The other is to use nested query. The meaning of nested query is to use join query. Part of the column is the attribute value of the A object, and the other part is the attribute value of the associated object B. The advantage is that only one SQL query can be sent The main object and its associated objects are detected.

So the question is, how to determine that the main object is 5 instead of 100 if 100 records are obtained by the join query? The principle of deduplication is that the <id> subtag in the <resultMap> tag specifies the id column that uniquely determines a record. Mybatis completes the deduplication function for 100 records according to the value of the <id> column. <id> can have Multiple, representing the semantic meaning of the joint primary key.

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

Example: The following join query shows 6 records. The first and second columns are the Teacher object columns, and the third column is the Student object column. After Mybatis de-duplication, 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 delayed loading? If so, what is its implementation principle?

Answer: Mybatis only supports lazy loading of association objects and collection objects. Association refers to one-to-one, 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 to use CGLIB to create the proxy object of the target object. When the target method is called, enter the interceptor method, such as calling a.getB().getName(), and the interceptor invoke() method finds that a.getB() is null value, then it will separately send the previously saved sql query associated with the B object, query B up, and then call a.setB(b), so the object b attribute of a has 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, including Hibernate, support lazy loading in the same principle.

The above interview questions have been sorted into documents. Friends who need to receive can   click me to receive the information for free . The benefits that the editor sends to you include the mybatis interview data collection, the Java core knowledge point data package, the Ali interview collection and other materials

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

Answer: For different Xml mapping files, if the namespace is configured, then the id can be repeated; if the namespace is not configured, then the id cannot be repeated; after all, the namespace is not required, 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 an id, and the duplicate id will cause the data to overwrite each other. With a namespace, id can be repeated naturally, and namespace+id is naturally different if the namespace is different.

 

 

12. How to execute batch processing in Mybatis?

Answer: Use BatchExecutor to complete batch processing.

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

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

BatchExecutor: Execute update (no select, JDBC batch processing does not support select), add all sql to the batch (addBatch()), wait for unified execution (executeBatch()), it caches multiple Statement objects, each Statement objects are all after the addBatch () is completed, waiting for the executeBatch () batch processing one by one. Same as JDBC batch processing.

Scope of action: These characteristics of Executor are strictly limited within the scope of the SqlSession life cycle.

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

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

15. Can Mybatis map Enum enumeration class?

Answer: Mybatis can map enumeration classes, not only enumeration classes, but Mybatis can map 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 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 embodied in two methods, setParameter() and getResult(), which respectively represent setting sql question mark placeholder parameters and obtaining columns search result.

16. In the Mybatis mapping file, if the A tag refers to 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 Xml mapping files in order, the quoted B tag can still be defined anywhere, and Mybatis can recognize it correctly.

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 resolved yet and does not exist yet. At this time, Mybatis will mark the A tag as an unresolved state, and then continue to parse the remaining tags, including B Labels. After all the labels are parsed, Mybatis will re-parse the labels that are marked as unresolved. At this time, when the A label is parsed, the B label already exists, and the A label can be resolved normally.

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

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? What is the difference between it and fully automatic?

Answer: Hibernate is a fully automatic ORM mapping tool. When you use Hibernate to query related objects or related collection objects, you can directly obtain them according to the object-relational model, so it is fully automatic. When Mybatis queries related objects or related collection objects, you need to manually write SQL to complete, so it is called a semi-automatic ORM mapping tool.

The interview questions seem to be very simple, but if you want to be able to answer correctly, you must be someone who has studied the source code and in-depth, rather than someone who only knows how to use it or someone who is familiar with it. All the above interview questions and their answers involve Content

19. What is Mybatis?

(1) Mybatis is a semi-ORM (Object Relational Mapping) framework, which encapsulates JDBC internally. You only need to pay attention to the SQL statement itself during development, and you don't need to spend energy to deal with complicated processes such as loading drivers, creating connections, and creating statements. The programmer directly writes the original ecological SQL, which can strictly control the SQL execution performance and has high flexibility.

(2) MyBatis can use XML or annotations to configure and map native information, and map POJOs to records in the database, avoiding almost all JDBC codes and manual setting of parameters and obtaining result sets.

(3) Configure the various statements to be executed through xml files or annotations, and generate the final executed SQL statements through the java object and the dynamic parameters of the SQL in the statement. Finally, the mybatis framework executes the SQL and maps the result to java object and return. (The process from executing sql to returning result).

20. Advantages of Mybaits:

answer:

1. Separate the Sql statement from Java.

2. It encapsulates the calls of the underlying JDBC and API, and can automatically convert the result set into JavaBean objects, simplifying the repetitive work of Java database programming.

3. Write Sql statements yourself, which is more flexible.

4. No need to use object encapsulation (or map encapsulation) when entering parameters, use @Param annotation

Another answer:

(1) Based on SQL statement programming, it is quite flexible and will not have any impact on the existing design of the application or database. SQL is written in XML, which releases the coupling between SQL and program code, which is convenient for unified management; XML tags are provided to support writing Dynamic SQL statements can be reused.

(2) Compared with JDBC, it reduces the amount of code by more than 50%, eliminates a large amount of redundant code in JDBC, and does not require manual switch connections;

(3) It is very compatible with various databases (because MyBatis uses JDBC to connect to the database, so as long as the database supported by JDBC is supported by MyBatis).

(4) It can be well integrated with Spring;

(5) Provide mapping tags to support ORM field relationship mapping between objects and databases; provide object relationship mapping tags to support maintenance of object relationship components.

21. Disadvantages of MyBatis framework:

(1) The workload of writing SQL statements is relatively large, especially when there are many fields and associated tables, there are certain requirements for developers to write 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 sufficiently flexible DAO layer solution.

(2) For projects that have high performance requirements or changes in demand, such as Internet projects, MyBatis will be a good choice.

22. What are the advantages and disadvantages of the ibatis/mybatis framework?

    Advantages: easy to learn and master

          sql is written in xml, which is convenient for unified management and optimization

  Uncouple sql and program code

  Provide object-relational mapping tags, support object-relationship establishment

  Provide xml tags, support writing dynamic sql

 

Disadvantages: low readability, debugging is very difficult, very limited, it is impossible to implement complex dynamic SQL splicing in the code according to logic like jdbc

23. The role of the ibatis core class; the role of the MyBatis core class?

    ibatis:

SqlMapClientBuilder: Load the configuration file and return a session

SqlMapClient: specific session

SqlSession: Add, delete, check and modify data

SqlMapSession: Perform database operations

SqlSessionManager: Create an object of SqlSesstion

SqlMapTransactionManager: Define transaction management functions

    Mybatis:

SqlSessionFactory The core of every MyBatis application

24. Comparison between mybatis/ibatis and hibernate;

Hibernate is fully automated, as long as the mapping file is configured, it can dynamically generate sql for us

ibatis is semi-automated, we need to write sql manually, ibatis is simple and easy to learn

Hibernate is more complicated, ibatis can be fine-grained optimization, and Hibernate is optimized according to the mapping file

8. What is the workflow or operating principle of ibatis?

answer:

25. The working principle of Mybatis:

1. Construct SqlSessionFactory from the mybatis-config.xml configuration file through SqlSessionFactoryBuilder.

2. SqlSessionFactory opens a SqlSession, obtains the Mapper object through the SqlSession instance and runs the Sql statement mapped by the Mapper.

3. Complete the CRUD operation and transaction commit of the database, and close the SqlSession.

Another answer:

1. Configure the database connection in the configuration file of sqlMapConfig.

2. Reference the sqlMap xml configuration file in the sqlMapConfig xml configuration file.

3. Configure the SQL file in the xml configuration file of sqlMap. (The file name is arbitrary, generally the class name of javaBean plus xml.)

4. Generate specific operations through SqlMapClient to manipulate the IBATIS object of the SQL file in the sqlMap configuration file.

5. The SqlMapClient object provides functions, and the parameters of the function correspond to replace the id, parameter and other attributes of the sqlMap configuration file to complete the execution of the SQL file

This concludes the article 

Xiaobian's benefits for you! ! !

The above interview questions have been sorted into documents. Friends who need to receive can  click me to receive the information for free  . The benefits that the editor sends to you include the mybatis interview information collection, the Java core knowledge point information package, the Ali interview collection and other information.

Follow the editor, the editor continues to update new content for you, thank you for your support! ! !

 

Guess you like

Origin blog.csdn.net/SQY0809/article/details/109367746