Today's topic-how to understand MyBatis (advantages & disadvantages) & detailed explanation of the use of MyBatis!

One, MyBatis

1. 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 on the complicated processes of loading drivers, creating connections, and creating statements. Programmers write native
SQL directly , which can strictly control SQL execution performance with 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).

2. The advantages and disadvantages of MyBatis

Advantages:
(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 and facilitates unified management; XML tags are provided, Supports the preparation of dynamic SQL statements and 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 need to switch connections manually;
(3) It is compatible with various databases (because MyBatis uses JDBC to connect 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 object relationship
component maintenance.
Disadvantages
(1) The workload of SQL statement writing is relatively large, especially when there are many fields and many 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.

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

#{} is pre-compilation processing, KaTeX parse error: Expected'EOF', got'#' at position 21: …string replacement. When Mybatis processes #̲{}, it replaces #{} in sql with... {}, it replaces ${} with the value of the variable.
Using #{} can effectively prevent SQL injection and improve system security.

4. What should I do when 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, the alias of the field name is consistent with the attribute name of the entity class.

<select id=”selectorder” parametertype=int” 
resultetype=”me.gacl.domain.order”> 
select order_id id, order_no orderno ,order_price price form orders where order_id=#{
    
    id};
 </select>

The second type: through to map the one-to-one correspondence between the field name and the entity class attribute name.

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

Mybatis uses the RowBounds object for paging, which is memory paging for the ResultSet result set, not physical paging.
You can write the parameters with physical paging directly in SQL to complete the physical paging function, or you can 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 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.

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

The first is to use tags to define the mapping relationship between database column names and object attribute names one by one.
The second is to use the alias function of the sql column to write the alias of the column as the object attribute name.
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.

7. How to perform batch insert?

First, create a simple insert statement:

<insert id=”insertname”> insert into names (name) values (#{
    
    value}) 
</insert>

Then execute batch insertion in the java code as follows:

list<string> names = new arraylist(); 
names.add(“fred”); 
names.add(“barney”); 
names.add(“betty”); 
names.add(“wilma”);
// 注意这里 executortype.batch 
sqlsession sqlsession = sqlsessionfactory.opensession(executortype.batch); 
try {
    
     
namemapper mapper = sqlsession.getmapper(namemapper.class); 
for (string name : names) {
    
     
mapper.insertname(name); 
}
sqlsession.commit();
 }catch(Exception e){
    
     
 e.printStackTrace(); 
 sqlSession.rollback(); 
 throw e; 
 }
 finally {
    
     
 sqlsession.close(); 
 }

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

,,,,, plus 9 tags of dynamic sql, among them are sql fragment tags, and sql fragments are introduced through tags to generate strategy tags for primary keys that do not support auto-increment.

9. There are several ways to realize one-to-one in MyBatis? How to operate?

There are joint query and nested query. The joint query is a joint query of several tables, which can be queried only once. It can be completed by configuring the association node in the resultMap to configure a one-to-one class;
nested query is to check a table first, according to this table The foreign key id of the result inside is used to query data in another table, which is also configured through association, but the query of another table is configured through the select attribute.

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

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.

11.Mybatis's primary and secondary caches:

1) Level 1 cache: HashMap local cache based on PerpetualCache. Its storage scope is Session. After Session is flushed or closed, all Caches in the Session will be emptied, and Level 1 cache is turned on by default.

2) The mechanism of the second-level cache is the same as that of the first-level cache. By default, PerpetualCache and HashMap storage are used. 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;

3) For the cache data update mechanism, when a C/U/D operation is performed in a certain scope (first-level cache Session/second-level cache Namespaces), by default all the caches in select under this scope will be cleared and merged Re-update, if the second-level cache is enabled, it will only be determined whether to refresh based on the configuration.

Guess you like

Origin blog.csdn.net/Java_Yhua/article/details/111387634