A, MyBatis

1. What is MyBatis

(1) Mybatis is a semi-ORM (Object Relational Mapping) framework, which encapsulates JDBC internally. During development, we only need to pay attention to THE SQL statement itself, and do not need to spend energy to deal with the complex process of loading drivers, creating connections, creating statements and so on. Programmers directly write the original ecological SQL, SQL execution performance can be strictly controlled, high flexibility.

(2) MyBatis can configure and map native information using XML or annotations to map POJOs to records in the database, avoiding almost all JDBC code and manually setting parameters and fetching result sets.

(3) Configure various statements to be executed through XML files or annotations, and map Java objects to the dynamic parameters of SQL in statements to generate the SQL statements to be executed. Finally, the MYBatis framework executes the SQL and maps the results to Java objects and returns them. (The process from executing SQL to returning result).

2. Advantages and disadvantages of MyBatis

Advantages:

(1) Based on SQL statement programming, quite flexible, will not cause any impact on the existing design of the application program or database, SQL written in XML, remove the COUPLING of SQL and program code, easy to unified management; Provides XML tags to support writing dynamic SQL statements and reuse.

(2) compared with JDBC, reduce more than 50% of the code, eliminate a lot of JDBC redundant code, do not need to manually switch the connection;

(3) very good compatibility with a variety of databases (because MyBatis uses JDBC to connect to the database, so as long as JDBC support database MyBatis support).

(4) Good integration with Spring;

(5) Provide mapping labels to support ORM field relational mapping between objects and databases; Provides object-relational mapping labels to support object-relational component maintenance.

disadvantages

(1) THE workload of SQL statement writing is large, especially when there are many fields and associated tables, there are certain requirements for developers to write SQL statement skills.

(2) SQL statements rely on the database, resulting in poor database portability, can not be replaced at will database.

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

KaTeX Parse Error: Expected ‘EOF’, got ‘#’ at position 21:… String to replace. SQL > select * from #̲{}; ${} replaces ${} with the value of the variable. Using #{} can effectively prevent SQL injection and improve system security.

4. What if the name of the attribute in the entity class is different from the name of the field in the table?

The first is to make the alias of the field name consistent with the attribute name of the entity class by defining the alias of the field name in the SQL statement of the query.

<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>Copy the code

The second is to map the one-to-one correspondence between field names and entity class attribute names.

5. How is Mybatis paginated? How does paging plug-ins work?

Mybatis uses the RowBounds object for paging, which is memory paging performed against a ResultSet ResultSet rather than physical paging. Physical paging can be done by writing parameters with physical paging directly in SQL, or physical paging can be done using paging plug-ins. The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in to intercept the SQL to be executed in the interception method of the plug-in, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect.

6. How does Mybatis encapsulate SQL execution results as target objects and return them? What are the mappings?

The first is to use tags to define the mapping between database column names and object attribute names one by one. The second is to use the SQL column alias function to write the column alias as the object property name. Mybatis creates objects by reflection after mapping between column names and attribute names. At the same time, Mybatis uses reflection to assign values to the attributes of the object one by one and returns them. The assignment cannot be completed for those attributes that cannot find the mapping relationship.

7, how to perform batch insert?

First, create a simple INSERT statement:

<insert ID = "insertname" > insert into names (name) values (#{value}) </insert>Copy the code

Then perform the batch insert in Java code as follows:

list<string> names = new arraylist(); Names. The add (" Fred "); Names. The add (" barney "); Names. The add (" Betty "); Names. The add (" Wilma "); / / note here 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(); }Copy the code

8, the Xml mapping file, in addition to the common select | insert | updae | delete tags, what other tags?

、、、、, plus 9 tags of dynamic SQL, including SQL fragment tags, which import SQL fragments through tags and generate policy labels for primary keys that do not support self-increment.

9. How many ways can MyBatis achieve one-to-one? How does it work?

There are joint query and nested query. 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 one-to-one classes. In a nested query, you can first query a table, and then query data in another table based on the foreign key ID of the result in the table, again using association configuration, but the query in the other table using select attribute configuration.

Does Mybatis support lazy loading? If so, how does it work?

Mybatis only supports lazy loading of association associative objects and collection associative objects. Association refers to one-to-one and collection refers to one-to-many queries. In Mybatis configuration file, you can configure whether to enable lazy-loading lazyLoadingEnabled = true | false.

The principle is that CGLIB is used to create a proxy object for the target object. When the target method is called, the interceptor method is entered, such as a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading.

Of course, not only Mybatis, almost all including Hibernate, support lazy loading principle is the same.

11. Mybatis level 1 and Level 2 cache:

1. Level 1 Cache: A HashMap local Cache based on PerpetualCache with Session scope. When Sessionflush or close, all caches in that Session are cleared, enabling Level 1 Cache by default.

Level 2 caches are PerpetualCache and HashMap by default. The difference is that the Mapper storage scope is PerpetualCache and you can customize the storage source, such as Ehcache. Level 2 caching is not enabled by default. To enable level 2 caching, use the Level 2 cache attribute class to implement the Serializable interface (which can be used to store the state of objects), which can be configured in its mapping file.

Caches are not updated by default when C/U/D is applied to a Session (level 1) or Namespaces (level 2). You can determine whether to refresh only based on the configuration.