Golden Nine Silver Ten Sprint-MyBatis Interview Topic (with answers)

Written in the front: The Java back-end advanced interview questions necessary for the interview in 2020. A review guide is summarized on Github. The content is detailed, with pictures and texts. Friends who need to learn can star!
GitHub address: https://github.com/abel-max/Java-Study-Note/tree/master

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 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 various statements to be executed by means of xml files or annotations, and generate the final executed SQL statements by mapping the java objects and the dynamic parameters of sql in the statement. Finally, the mybatis framework executes sql and maps the results as java object and return. (The process from executing sql to returning result).

2. The advantages of Mybaits

(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 decouples SQL and program code and facilitates 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 need to manually switch connections;
(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.

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

5. What is the difference between MyBatis and Hibernate?

(1) Mybatis is different from hibernate, it is not exactly an ORM framework, because MyBatis requires programmers to write Sql statements.
(2) Mybatis directly writes the original ecological SQL, which can strictly control the execution performance of SQL, and has high flexibility. It is very suitable for software development that does not require high requirements for relational data models, because the requirements of this type of software change frequently, and once the requirements change require rapid output. . But the premise of flexibility is that mybatis cannot be database-independent. If you need to implement software that supports multiple databases, you need to customize multiple sets of sql mapping files, which is a lot of work.
(3) Hibernate has strong object/relational mapping capabilities and good database independence. For software with high requirements for relational models, if you use hibernate to develop software, you can save a lot of code and improve efficiency.

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

{} is precompilation processing, $ {} is string replacement

When Mybatis is processing #{}, it will replace #{} in sql with a?
Sign , and call the set method of PreparedStatement to assign a value; when Mybatis is processing , it will be {}, which isWhen , it is the {} replace the value of the variable.
Using #{} can effectively prevent SQL injection and improve system security.

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

Type 2: Through 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.order” id=”orderresultmap”>
<!–用 id 属性来映射主键字段–>
<id property=”id” column=”order_id”>
<!–用 result 属性来映射非主键字段,property 为实体类属性名,column
为数据表中的属性–>
<result property = “orderno” column =”order_no”/>
<result property=”price” column=”order_price” />
</reslutMap>

8. How to write like statement in fuzzy query?

Type 1: Add sql wildcard in Java code.

string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like #{value}
</select>

Type 2: Splicing wildcards in sql statements will cause sql injection

string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like "%"#{value}"%"
</select>

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

The Dao interface is the Mapper interface. 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 Statement of the Mapper 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 interface full name + method name spliced ​​string as the key value can uniquely locate a MapperStatement. In Mybatis, each,, and label will be parsed as a MapperStatement object.

For example: com.mybatis3.mappers.StudentDao.findStudentById, the only MapperStatement whose namespace is com.mybatis3.mappers.StudentDao and whose id is findStudentById can be found.
The methods in the Mapper interface cannot be overloaded, because the storage and search strategy of fully qualified name + method name is used. 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.

10. How does Mybatis pagination? 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

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

12. How to perform bulk insert?

First, create a simple insert statement:

<insert id=”insertname”>
insert into names (name) values (#{value})
</insert>
然后在 java 代码中像下面这样执行批处理插入:
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();
}

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

The insert method always returns an int value, which represents the number of rows inserted.
If the self-growth strategy is adopted, the automatically generated key value can be set to the passed parameter object after the insert method is executed.
Example:

<insert id=”insertname” usegeneratedkeys=”true” keyproperty=”
id”>
insert into names (name) values (#{name})
</insert>
name name = new name();
name.setname(“fred”);
int rows = mapper.insertname(name);
// 完成后,id 已经被设置到对象中
system.out.println(“rows inserted = ” + rows);
system.out.println(“generated key value = ” + name.getid());

14. How to pass multiple parameters in mapper?

1. The first type:
DAO layer function
public UserselectUser(String name, String area);
corresponding xml, #{0} represents the first parameter in the dao layer, #{1} represents the first parameter in the dao layer Two parameters, more parameters can be added later.

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

2. The second type: use @param annotation:

public interface usermapper {
user selectuser(@param(“username”) string
username,@param(“hashedpassword”) string hashedpassword);
}

Then, it can be used in xml like the following (recommended to be packaged as a map and passed to the mapper as a single parameter):

<select id=”selectuser” resulttype=”user”>
select id, username, hashedpassword
from some_table
where username = #{username}
and hashedpassword = #{hashedpassword}
</select>

3. The third type: multiple parameters are encapsulated into a map

try {
//映射文件的命名空间.SQL 片段的 ID,就可以调用对应的映射文件中的
SQL
//由于我们的参数超过了两个,而方法中只有一个 Object 参数收集,因此
我们使用 Map 集合来装载我们的参数
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();
}

15. What is the use of Mybatis dynamic sql? How does it work? What are the dynamic SQL?

Mybatis dynamic sql can write dynamic sql in the form of tags in the Xml mapping file. The execution principle is to complete the logical judgment based on the value of the expression and dynamically splice the sql function.
Mybatis provides 9 kinds of dynamic sql tags: trim | where | set | foreach | if | choose
| when | otherwise | bind.

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

Answer: ,,,, and 9 tags of dynamic sql are added, among which are sql fragment tags. SQL fragments are introduced through tags to generate strategy tags for primary keys that do not support auto-increment.

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

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; the
reason is that namespace+id is used as the key of Map <String, MapperStatement>
, if there is no namespace, there is nothing left Under id, then duplicate id will cause data to overwrite each other.
With a namespace, the id can be repeated naturally, and the namespace+id is naturally different if the namespace is different.

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

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 relationship model, so it is fully automated. 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.

19. One-to-one, one-to-many related queries?

<mapper namespace="com.lcb.mapping.userMapper">
<!--association 一对一关联查询 -->
<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">
<!-- 实体类的字段名和数据表的字段名映射 -->
<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 一对多关联查询 -->
<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>

20. How many ways does MyBatis implement one-to-one? How do you do it?

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

21. There are several ways to realize one-to-many in MyBatis, how to operate?

There are joint queries and nested queries. A joint query is a joint query of several tables, which is only queried once.
It can be completed by configuring a one-to-many class in the collection node in the resultMap; a nested query is to check a table first, according to the foreign key id of the result in the table, To query data in another table is also configured through collection, but the query of another table is configured through the select node.

22. Does Mybatis support lazy 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 query. 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(), 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.

23, Mybatis's primary and secondary cache

1) Level 1 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 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 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;
3) For the cache data update mechanism , When
the C/U/D operation is performed in a certain scope (first-level cache Session/second-level cache Namespaces), all caches in select under this scope will be cleared by default.

24. What is the interface binding of MyBatis? What are the ways to achieve it?

Interface binding is to define the interface arbitrarily in MyBatis, and then bind the methods in the interface to the SQL statement, we can directly call the interface method, so that we can have more flexible choices and settings than the original method provided by SqlSession .
There are two ways to implement interface binding. One is to bind via annotations, which is to add @Select, @Update and other annotations to the interface methods, which contain Sql statements to bind; the other is to write SQL in xml To bind, in this case, the namespace in the xml mapping file must be the full path name of the interface. When the Sql statement is relatively simple, use annotation binding, when the SQL statement is more complex, use xml binding, generally use xml binding more.

25. What are the requirements when using the mapper interface of MyBatis to call?

1. The Mapper interface method name is the same as the id of each SQL defined in mapper.xml;
2. The input parameter type of the Mapper interface method is the
same as the parameterType of each SQL defined in mapper.xml ;
3. The type of the Mapper interface method The output parameter type
is the same as the resultType of each SQL defined in mapper.xml ;
4. The namespace in the Mapper.xml file is the class path of the mapper interface.

26. What are the ways to write Mapper?

The first: the interface implementation class inherits SqlSessionDaoSupport: to use this method, you need to write the
mapper interface, the mapper interface implementation class, and the mapper.xml file.
(1) Configure the location of mapper.xml in sqlMapConfig.xml

<mappers>
<mapper resource="mapper.xml 文件的地址" />
<mapper resource="mapper.xml 文件的地址" />
</mappers>

(2) Define the mapper interface
(3) In the implementation of class integration SqlSessionDaoSupport
mapper method, this.getSqlSession() can be used to add, delete, modify and check data.
(4) Spring configuration

<bean id=" " class="mapper 接口的实现">
<property name="sqlSessionFactory"
ref="sqlSessionFactory"></property>
</bean>

The second: use org.mybatis.spring.mapper.MapperFactoryBean:
(1) Configure the location of mapper.xml in sqlMapConfig.xml. If mapper.xml and mappre interface have the same name and are in the same directory, there is no need to configure

<mappers>
<mapper resource="mapper.xml 文件的地址" />
<mapper resource="mapper.xml 文件的地址" />
</mappers>

(2) Define the mapper interface:
1. The namespace in mapper.xml is the address
of the mapper interface 2. The method name in the mapper interface is consistent with the id of the statement defined in mapper.xml 3. The definition in
Spring

<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="mapper 接口地址" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

The third type: use the mapper scanner:
(1) Write the mapper.xml file:
the namespace in mapper.xml is the address of the mapper interface; the method name in the mapper interface is consistent with the id of the statement defined in mapper.xml; if Keeping the name of mapper.xml and mapper interface consistent does not need to be configured in sqlMapConfig.xml.
(2) Define the mapper interface:
Note that the file name of mapper.xml is consistent with the interface name of the mapper and is placed in the same directory
(3) Configure the mapper scanner:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper 接口包地址
"></property>
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory"/>
</bean>

(4) Obtain the mapper implementation object from the spring container after using the scanner.

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

Guess you like

Origin blog.csdn.net/doubututou/article/details/109128923