2021 MyBatis core interview questions

First of all, Mybatis is an excellent persistence layer ORM framework, which encapsulates the process of operating the database of jdbc, so that developers only need to pay attention to SQL itself. No need to spend energy to deal with some repetitive and tedious steps. Finally, the final executed SQL statement is generated by mapping the java object and the SQL in the statement. Finally, the mysql framework executes sql and maps the result to a java object and returns it.

ORM: Object-relational mapping. Simply put, it is to establish a mapping relationship between the tables in the database and the objects in Java, which allows us to manipulate objects to indirectly manipulate the database.

Semi-ORM: When querying related objects or related collection objects, you need to manually write SQL to complete.

MyBatis programming steps

  • Create SqlSessionFactory
  • Create SqlSession through SqlSessionFactory
  • Perform database operations through sqlsession
  • Call session.commit() to commit the transaction
  • Call session.close to close the session

How MyBatis works

  • Read the MyBatis configuration file. (Get information such as the operating environment of MyBatis)
  • Load the mapping file. (SQL mapping file, which is configured with SQL statements for operating the database)
  • Construct a session factory: construct a session factory SqlSessionFactory through configuration information such as the MyBatis environment
  • Create session object: There is a session factory to create a SqlSession object, which includes all methods for executing SQL statements
  • Executor executor: dynamically generates the SQL statements that need to be executed according to the parameters passed by the SqlSession, and is responsible for the maintenance of the query cache
  • Mappedstatement object: used to store the id, parameters and other information of the SQL statement to be mapped
  • Input parameter mapping: The parameter type can be a collection type such as Map, List, etc., and can also use basic data types and POJO types
  • Output result mapping: similar to input.

Advantages of MyBatis

  • Programming based on SQL statements is quite flexible. SQL is written in XML, which decouples sql and program code, facilitating unified management. Provides XML tags, supports the writing of dynamic SQL statements, and can be reused
  • Eliminate a lot of redundant JDBC code, no need to manually switch the connection;
  • Good compatibility with various databases
  • Able to integrate well with Spring;
  • Provide mapping tags to support ORM field relationship mapping between objects and databases; provide object-relational mapping tags to support object-relational component maintenance.

Disadvantages of the MyBatis framework

  • The writing workload of SQL statements is relatively large, especially when there are many fields and associated tables, there are certain requirements for developers to write SQL statements.
  • SQL statements depend on the database, resulting in poor database portability, and the database cannot be replaced at will.

What are the differences between MyBatis and Hibernate

  • MyBatis is a semi-ORM framework, you need to write SQL statements yourself, which is highly flexible, but you need to customize multiple sets of SQL mapping files, which is a lot of work.
  • Hibernate database has good independence, saves code and improves efficiency

The difference between #{} and ${}

  • #{}: It is pre-compilation processing. Will #{} in sql be replaced with? , Call the set method of PreoaredStatement to assign
  • ${}: is a string replacement, used in tag attribute values ​​and sql internals, and belongs to static text replacement. Replace ${} with the value of the variable.

Using #{} can effectively prevent SQL injection and improve the security of the system.

What to do when the attribute name of the entity class is inconsistent with the field name in the table

  • By defining the alias of the field name in the query sql statement, the alias of the field name is consistent with the attribute name of the entity class.

  • One-to-one correspondence between field names and entity class attribute names through class mapping

How to write fuzzy query like

  • Add sql wildcard in Java code
  • Splicing wildcards in SQL statements (but it will cause SQL injection problems)

Usually an Xml mapping file will write a Dao interface corresponding to it. So what is the working principle of the Dao interface.

The Dao interface is the Mapper interface.

  • The fully qualified name of the interface is the value of the namespace of the mapping file
  • The method name of the interface is the id value of the Mapper's Statement in the mapping file
  • The parameters in the interface method are the parameters passed to sql

The Mapper interface has no implementation class. When the interface method is called, the fully qualified name of the interface + the method name spliced ​​string as the key value can uniquely locate a MapperStatement. In MyBatis, each

  • ,,, and tags will be parsed as a method of the Dao interface of a MapperStatement object. When the parameters are different, can the method be overloaded? The method in the Mapper interface cannot be overloaded because the fully qualified name + method name save and search strategy . So it cannot be overloaded. The working principle of the Mapper interface is the JDK dynamic proxy. MyBatis will use the JDK dynamic proxy to generate the proxy object proxy for the Mapper interface when running. The proxy object will intercept the interface method and execute the sql represented by the MapperStatement instead, and then return the sql execution result. How does MyBatis perform paging and what is the principle of the paging plug-in MyBatis uses RowBounds objects for paging, which is memory paging performed for the ResultSet result set, not physical paging. You can directly write the parameters with physical paging in SQL to complete the physical paging function, or use the paging plug-in to complete the physical paging. The basic principle of the paging plug-in is to use the plug-in interface provided by MyBatis to implement custom plug-ins and intercept methods in the plug-ins. Internally intercept the SQL to be executed, then rewrite the SQL, and add the corresponding physical paging statement and physical paging parameters according to dialect. How does Mybati encapsulate the sql execution mechanism as an object and return it? Which mapping forms use tags to define the mapping relationship between database column names and object attribute names one by one. Use the alias function of the sql column to write the column alias as the object attribute name. After the mapping relationship between the column name and the attribute name is established, MyBatis creates the object through reflection, and at the same time uses the reflection to assign and return the attributes of the object one by one. Those who cannot find the mapping relationship The attribute of is unable to complete the assignment. How to perform batch insertion. How to obtain the automatically generated primary key value. Use the JDBC built-in method to query after inserting to obtain the query before inserting to obtain the primary key. How to pass multiple parameters in the mapper. Dao layer functions use @param to annotate multiple The parameters are encapsulated into map MyBatis dynamic sql MyBatis dynamic sql can be written in the form of a label in the Xml mapping file. The execution principle is to complete the logical judgment and dynamically splice the sql function according to the value of the expression. MyBatis provides nine kinds of sql tags trim where set foreach if choose when otherwise bind XML file tags select insert update delete resultMap parameterMap sql include selectKey In the Xml mapping file of MyBatis, can the id of different Xml files be repeated. If the namespace is configured, the id can be repeated. If the namespace is not configured, the id can not be repeated. There are several ways to jointly query several tables. The query is performed only once. By configuring the nested query of the collection node, first check one table, and then query the data in another table according to the found id. It is also by configuring the collection, but for the other table. Query whether MyBatis supports lazy loading through the select node configuration, and how to realize that Mybatis only supports the lazy loading of association objects and collection objects. It can be configured by configuring lazyLoadingEnabled. Principle 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(), the interceptor invoke() method finds that a.getB() is a null value, then It will separately send the sql saved in advance to query the associated B object, query B, 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. MyBatis's first level cache: HashMap local cache based on PerpetualCache, its storage scope is Session. After Session flush or close, all Caches in the Session will be emptied, and the first level cache is turned on by default. The mechanism of the second-level cache is the same as that of the first-level cache. By default, PerpetualCache and HashMap are used for storage. The difference is that the storage scope is Mapper (Namespace), and the storage source can be customized, such as Ehcache. The second-level cache is not turned on by default. To enable the second-level cache, the use of the second-level cache attribute class needs to implement the Serializable serialization interface (which can be used to save the state of the object), which can be configured in its mapping file; the cache update is added, deleted, changed, and cleared. Method setting clear property MyBatis interface binding, and implementation method Interface binding: Define the interface arbitrarily in MyBatis, and then bind the method in the interface to the SQL statement, and we can directly call the interface method when we use it. The way is to bind by annotation and bind by writing SQL statements in xml. You need to specify that the namespace in xml must be the full path name of the interface. When calling the mapper interface of Mybatis, what are the requirements that the method name of the Mapper interface and the id of the sql in mapper.xml are the same. The type is the same as the type of the resultType of each SQL defined in mapper.xml Mapper. The namespace in the xml file is the operating principle of the Mybatis plug-in of the classpath of the mapper interface, and how to write a plug-in. 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 interface objects are executed Method, it will enter the interception method, specifically the invoke() method of InvocationHandler. Of course, only those methods that you specify to be intercepted will be intercepted. Write a plug-in: 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. Pre-compilation definition SQL pre-compilation means that the database driver compiles the SQL statement before sending the SQL statement and parameters to the DBMS, so that when the DBMS executes the SQL, it does not need to reproduce the pre-compilation effect to optimize the execution of the SQL. Most of the pre-compiled SQL can be run directly, and the pre-compiled statement object can be reused. It can also prevent SQL injection into MyBatis which Executor executors, and what is the difference between them. There are three basic Executor executors: SimpleExecutor, ReuseExxecutor, BatchExecutor. SimpleExecutor opens a Statement object every time an update or select is executed, and it closes immediately when it is used up. ReuseRxecutor executes update or select, and uses sql as the key to find the Statement object. In order to repeatedly use the Statement object BatchExecutor to execute the update, all sql are added to the batch and wait for the same execution. There are multiple Statement objects in its soul village. What to do when the attribute name in the entity class is different from the field name in the table By defining the alias of the field name in the query SQL statement, the field name and the attribute name of the entity class are consistent. The resultMap is used to map the one-to-one relationship between the field name and the attribute name of the entity class. The difference between ResultType and ResultMap is the first of all MyBatis performs select mapping in the query When, the return type can be resultType or resultMap, where resultType directly represents the return type, and resultMap is a reference to an external ResultMap. These two cannot exist at the same time. When MyBatis performs query mapping, in fact, every attribute queried is placed in a corresponding Map, the key is the attribute name, and the value is the corresponding value. Finally, if you feel that you are rewarded after reading, I hope to pay attention to it. By the way, give me a thumbs up. This will be the biggest motivation for my update. Thank you for your support. Welcome everyone to pay attention to my public account [java 場狐] and focus on java. And the basic knowledge of computer, to ensure that you will get something after reading it, if you don’t believe it, please call me for one-click triple connection: like, forward, and watching. If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love. ——I am Chuhu, and I love programming as much as you. Welcome to follow the public account "Java Fox" for the latest news If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love. ——I am Chuhu, and I love programming as much as you. Welcome to follow the public account "Java Fox" for the latest news If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love. ——I am Chuhu, and I love programming as much as you. Welcome to follow the public account "Java Fox" for the latest news
  • Guess you like

    Origin blog.csdn.net/issunmingzhi/article/details/114441738