Last time I shared 50 micro service interview details, this time I will bring you 27 MyBatis interview details

【 Prepare for spring recruitment series 】50 micro service interview questions in detail

1. What is Mybatis?

1. Mybatis is a semi-ORM (Object relational Mapping) framework, which encapsulates JDBC internally. When developing, it only needs to pay attention to THE SQL statement itself. SQL execution performance can be strictly controlled with 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 the statements to be executed through XML files or annotations, and map Java objects to the dynamic parameters of the SQL in the statement to generate the final SQL statement. 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 of Mybaits:

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 that support writing dynamic SQL statements and can be reused.

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, 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.

3. Disadvantages of MyBatis framework:

1, SQL statement writing workload is large, especially when the field, associated table, for developers to write SQL statement skills have certain requirements.

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

4, MyBatis framework applicable occasions:

MyBatis focuses on SQL itself and is a flexible DAO layer solution.

2. MyBatis will be a good choice for projects with high performance requirements or more variable requirements, such as Internet projects

5. What are the differences between MyBatis and Hibernate?

1. Unlike Hibernate, Mybatis is not a complete ORM framework because Mybatis requires programmers to write their own Sql statements.

2, Mybatis directly write the original SQL, SQL execution performance can be strictly controlled, high flexibility, very suitable for the software development of relational data model requirements are not high, because this kind of software demand changes frequently, but a demand change requires rapid output results. However, the premise of flexibility is that Mybatis cannot achieve database independence. If you need to implement software supporting a variety of databases, you need to customize multiple sets of SQL mapping files, and the workload is heavy.

Hibernate object/relational mapping ability, database independence is good, for software with high requirements of relational model, if Hibernate development can save a lot of code, improve efficiency.

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

#{} is precompiled processing, and ${} is string substitution.

Mybatis will replace #{} with? Call the set method in PreparedStatement to assign the value.

${} = ${};

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

7, 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 orderswhere order_id=#{id};
</select> Copy the code

Second: use

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

<select id="getOrder" parameterType="int"
resultMap="orderresultmap">
select * from orders where order_id=#{id}
</select>
<resultMap type= "me. Gacl. Domain. The order" id = "orderresultmap" > <! > < ID property= "ID" column= "order_id" > <! -- Use the result attribute to map non-primary key fields. Property is the name of the entity class attribute. Column is an attribute in the data table -- > <result property= "orderno" column= "order_no" /> <result property= "price" column= "order_price" /> </reslutMap>Copy the code

8, fuzzy query like statement how to write?

Type 1: Add SQL wildcards to Java code.

Smi string wildcardname = "% %"; list<name> names = mapper.selectlike(wildcardname); <select id= "selectlike" > select * from foowhere bar like #{value}
</select>Copy the code

2. Concatenate wildcards in SQL statements, which causes SQL injection

String wildcardname = "smi"; list<name> names = mapper.selectlike(wildcardname); <select id= "selectlike" > select * from foowhere bar like "%"#{value}"%"
</select>Copy the code

9. Usually, an Xml mapping file will write a Dao interface corresponding to it. What is the working principle of this Dao interface? Can methods in the Dao interface be overloaded if their parameters are different?

Dao interfaces are Mapper interfaces. The full name of the interface is the value of namespace in the mapping file.
The method name of the interface is the ID of the Statement of the Mapper in the mapping file. Inside the interface method
Parameters are the parameters passed to SQL.
The Mapper interface has no implementation class. When an interface method is called, the interface name + method name concatenation string is used as the key value to uniquely locate a MapperStatement. In Mybatis, each < SELECT >, < INSERT >,

, < DELETE > tag is parsed into a MapperStatement object.

For example: Com. Mybatis3. Mappers ^ tudentDao findStudentByld, can only find the namespace for co m.m ybatis3. Map PE rs. Stud ent Dao id as below findStudentByld MapperStatement.

Methods in the Mapper interface cannot be overridden because they use the save and find strategy of the full name + method name. Mybatis will use JDK dynamic proxy to generate proxy object for Mapper interface. The proxy object will intercept the interface method, execute the SQL represented by MapperStatement, and return the SQL execution result.

How does Mybatis paginate? How does paging plug-ins work?

Mybatis uses the RowBounds object to talk about row paging, which is memory paging performed against ResultSet result sets rather than physical paging. You can write parameters with physical paging directly in SQL to complete physical paging, or you can use paging broadcast pieces to complete physical paging.

The basic principle of paging multicast 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’s column intercept method, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect.

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

The first is to use the

tag 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.

How do I perform batch inserts?

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

13. How to obtain the automatically generated (primary) key value?

The insert method always returns an int that represents the number of rows inserted.

With a self-growth strategy, automatically generated key values can be set to the parameter object passed in after the INSERT method.

Example:

< insert insertname usegeneratedkeys = "id =" "true"Keyproperty =" id "> insert into names (name) values (#{name})</insert> name name = new name(); Name. Elegantly-named setname (" Fred "); int rows = mapper.insertname(name); // When done, the ID has been set to the object system.out.println(" rows = "+ rows); System.out. println(" generated key value = "+ name.getid());Copy the code

14. How to pass multiple parameters in Mapper?

1. The first kind:
DAO layer functions

public UserselectUser(String name,String area); The corresponding XML,#{0} represents the first parameter received in the DAO layer, and #{1} represents the second parameter received in the DAO layerParameters, more parameters can be added later.Copy the code

<select id="selectUser"resultMap="BaseResultMap">
select * fromuser_user_t whereuser_name = # {0}
anduser_area=# {1}
</select> Copy the code

2. Use @param annotations:

Public interface usermapper {user selectUser (@param(" username ") string username,@param(" hashedPassword ") string hashedpassword); }Copy the code

It can then be used in XML like this (encapsulated as a map is recommended and passed as a single parameter to Mapper):

<select ID = "selectUser" resultType = "user" > select ID, username, hashedPassword from some_tablewhere username = #{username}
and hashedpassword = #{hashedpassword}
</select> Copy the code

3. Third: Encapsulate multiple parameters into a Map

Try {// Map the file namespace. // Since we have more than two parameters, and only one Object parameter is collected in the method, So we use the Map collection to load our parameters Map < String, Object > Map = new HashMap(); map.put("start", start);
map.put("end", end);
return sqlSession.selectList("StudentID.pagination", map);
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
throw e;
} finally {
MybatisUtil.closeSqlSession();
} Copy the code

15, Mybatis dynamic SQL what to use? How does it work? What dynamic SQL is there?

Mybatis dynamic SQL can be in THE Xml mapping file, in the form of the preparation of dynamic SQL tags, execution principle
Is based on the value of the expression to complete the logical judgment and dynamic concatenation SQL function.
Mybatis provides nine dynamic SQL tags: trim | where | set | foreach | if | choose
| s | otherwise | bind.

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

Answer:

, , < SQL >,

,

, plus nine tags for dynamic SQL, where < SQL > is the SQL fragment tag, through
The

tag introduces SQL fragments, and

generates policy labels for primary keys that do not support self-increment

To sign.

17. In the Xml mapping files of Mybatis, can the IDS of different Xml mapping files be repeated?

Different Xml mapping files, if configured with namespace, then the ID can be repeated; If no namespace is configured, the ID must be unique.
Namespace + ID is used as the key of Map

. If there is no namespace, only ids are left. Duplicate ids will overwrite each other. With a namespace, the natural ID can be repeated. With different namespaces, the namespace+ ID will naturally be different.
,>

Why Mybatis is a semi-automatic ORM mapping tool? What’s the difference between it and automatic?

Hibernate is a fully automated ORM mapping tool. When using Hibernate to query associated objects or associated collection objects, it can be directly retrieved based on the object relational model, so it is fully automated. While Mybatis needs to write SQL manually when querying associated objects or associated collection objects, so it is called semi-automatic ORM mapping tool.

19, one to one, one to many associated query?

<mapper namespace="com.lcb.mapping.userMapper"> <! --association one-to-one associative query --><select id="getClass" parameterType="int"
resultMap="ClassesResultMap">
select * from class c,teacher t where c.teacher_id=t.t_id and
c.c_id=#{id}
</select>
<resultMap type="com.lcb.user.Classes" id="ClassesResultMap"> <! -- mapping entity class field names to data table field names --> <id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher"
javaType="com.lcb.user.Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/> </association> </resultMap> <! --collection 1 to many associative query --> <select id="getClass2" parameterType="int"
resultMap="ClassesResultMap2">
select * from class c,teacher t,student s where c.teacher_id=t.t_id
and c.c_id=s.class_id and c.c_id=#{id}
</select>
<resultMap type="com.lcb.user.Classes" id="ClassesResultMap2">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher"
javaType="com.lcb.user.Teacher">
<id property="id" column="t_id"/><result property="name" column="t_name"/>
</association>
<collection property="student"
ofType="com.lcb.user.Student">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
</collection>
</resultMap>
</mapper> Copy the code

20. 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.

21, MyBatis has several ways to achieve one-to-many, how to operate?

There are federated and nested queries. Joint query is a joint query of several tables, which is only queried once. It can be completed by configuring one-to-many classes in the Collection node in the resultMap. The nested query is to first query a table, according to the foreign key ID of the result in the table, to query data in another table, also through the configuration of collection, but the query of the other table through the select node configuration.

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

A: Mybatis only supports lazy loading of association associative objects and collection associative objects. Association refers to one-to-one query and collection refers to one-to-many query. 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.

23, Mybatis level 1, level 2 cache:

1) Level 1 Cache: A HashMap local Cache based on PerpetualCache, which is stored at Session scope. When a Session is flushed or closed, all caches in that Session are cleared and Level 1 Cache is enabled by default.
2) The mechanism for tier 2 cache is the same as that for Tier 1 cache, which is PerpetualCache and HashMap by default. The difference is that the storage scope is Mapper(Namespace) and the storage source can be customized, such as Ehcache. Level 2 cache is not enabled by default. To enable level 2 cache, use the Level 2 cache attribute class to implement the Serializable interface (which can be used to store the state of objects). You can configure
in its mapping file.
If C/U/D has been applied to a select area (Session level 1 / Namespaces level 2), the cache will be cleared by default.

24, What is MyBatis interface binding? What are the implementation methods?

Interface binding is to define any interface in MyBatis and bind the methods in the interface to SQL statements. We can call interface methods directly, so that we can have more flexible choices and Settings compared with the methods provided by SqlSession.
Interface binding can be implemented in two ways. One is through annotation binding, which is to add @SELECT, @update and other annotations to the interface methods, which contain Sql statements to bind. The other option is to bind by writing SQL in XML. In this case, to specify the namespace in the XML mapping file must be the full path name of the interface. When Sql statements are simple, annotations are used for binding. When Sql statements are complex, XML is used for binding. XML is often used for binding.

25. What are the requirements when using Mapper interface of MyBatis?

Mapper interface method name is the same as the ID of each SQL defined in mapper.xml.
The input parameter types of Mapper interface methods are the same as those of parameterType for each SQL defined in mapper.xml.
3. The output parameter type of the Mapper interface method is the same as the resultType type of each SQL defined in mapper.xml;
4. Namespace in mapper. XML file is the classpath of Mapper interface.

26. What are the ways to write Mapper?

SqlSessionDaoSupport: This method needs to be written

Mapper interface, mapper interface implementation class, mapper.xml file.

1. Configure the location of mapper. XML in sqlmapconfig. XML

<mappers>
<mapper resource="Address of mapper. XML file" />
<mapper resource="Address of mapper. XML file" />
</mappers> Copy the code

2. Define the Mapper interface
SqlSessionDaoSupport
This.getsqlsession () can be used to add, delete, modify or query data in mapper.
4. Spring configuration

<bean id="" class="Implementation of mapper Interface">
<property name="sqlSessionFactory"
ref="sqlSessionFactory"></property>
</bean>Copy the code

The second: use the org. Mybatis. Spring. Mapper. MapperFactoryBean:

1. Configure the location of mapper. XML in sqlmapconfig. XML

<mappers>
<mapper resource="Address of mapper. XML file" />
<mapper resource="Address of mapper. XML file" />
</mappers>Copy the code

2. Define mapper interface:
1. Namespace in mapper. XML indicates the address of the mapper interface
2. The method name in the mapper interface must be the same as the ID of the statement defined in mapper. XML
3. Defined in Spring

<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="Mapper interface address" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>Copy the code

Third: Using mapper scanner:

1. Mapper. XML file preparation:
The namespace in mapper. XML indicates the address of the mapper interface. The method name in the mapper interface must be the same as the ID of the statement defined in mapper. XML. If the mapper. XML and mapper interface names are the same, you do not need to configure them in sqlmapconfig. XML.
2. Define mapper interface:
Note that the file name of mapper. XML is the same as the interface name of mapper and is placed in the same directory
3. Configure mapper scanner:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="Mapper interface packet address"></property>
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory"/>
</bean>Copy the code

4. Get the mapper implementation object from the Spring container after using the scanner.

27. Describe the operation principle of Mybatis plug-in and how to write a plug-in.

A: Mybatis can only be written for ParameterHandler, ResultSetHandler,
Mybatis uses JDK dynamic proxy to generate proxy objects for the interface that needs to be intercepted to implement the intercepting function. When executing the methods of these four interface objects, the intercepting method will enter. This is the Invoke () method of InvocationHandler, which, of course, intercepts only those methods that you specify need to be intercepted.
Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor



Finally:

Mybatis interview details here, there is an opportunity to prepare for spring recruitment in the back of the series of topics will share micro services, ZooKeeper, Dubbo, Kafka and other interview topics. I also summarized all the topics in a PDF document

The whole series of about 1000 interviews full explanation, need source documents can follow wechat public number: Java programmers gathering place.