preface
MyBatis is an excellent persistence layer ORM framework, which encapsulates the process of JDBC operation database, so that developers only need to pay attention to SQL itself, You do not need to spend effort to deal with JDBC complex process code such as driver registration, connection creation, statement creation, manual parameter setting, result set retrieval, etc.
Mybatis configures the statement to be executed through XML or annotations, maps the SQL statement to Java objects, and generates the SQL statement to be executed. Finally, Mybatis framework executes SQL, maps the result to Java objects, and returns the statement.
MyBatis knowledge points summed up a mind map to share with you
MyBatis interview questions
1. What is Mybatis?
2. Advantages of Mybaits:
3. Disadvantages of MyBatis framework:
4, MyBatis framework applicable occasions:
5. What are the differences between MyBatis and Hibernate?
What is the difference between #{} and ${}?
7, What if the name of the attribute in the entity class is different from the name of the field in the table?
8, fuzzy query like statement how to write?
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?
How does Mybatis paginate? How does paging plug-ins work?
How does Mybatis encapsulate SQL execution results as target objects and return them? What are the mappings?
How do I perform batch inserts?
13. How to obtain the automatically generated (primary) key value?
14. How to pass multiple parameters in Mapper?
15, Mybatis dynamic SQL what to use? How does it work? What dynamic SQL is there?
16, Xml mapping file, in addition to the common select | insert | updae | delete tags, what other tags?
Why Mybatis is a semi-automatic ORM mapping tool? What’s the difference between it and automatic?
19, one to one, one to many associated query?
20. How many ways can MyBatis achieve one-to-one? How does it work?
21, MyBatis has several ways to achieve one-to-many, how to operate?
Does Mybatis support lazy loading? If so, how does it work?
23, Mybatis level 1, level 2 cache
24, What is MyBatis interface binding? What are the implementation methods?
25. What are the requirements when using Mapper interface of MyBatis?
26. What are the ways to write Mapper?
27, Describe the operation principle of Mybatis plug-in, and how to write a plug-in
MyBatis interview questions
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 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 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) 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.
3. Disadvantages of MyBatis framework:
(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.
4, MyBatis framework applicable occasions:
(1) 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 writes the original SQL, which can strictly control the PERFORMANCE of SQL execution and has high flexibility. It is very suitable for software development with low requirements on relational data model, because such software needs to change frequently and output results rapidly once the requirements change. 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.
(3) Hibernate object/relational mapping ability is strong, 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.
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. The parameters in the interface method 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.
, < DELETE > tag is parsed into a MapperStatement object.
For example: Com. Mybatis3. Mappers. StudentDao. FindStudentById, Can only find the namespace for the com. Mybatis3. Mappers. StudentDao id for findStudentById MapperStatement below.
Methods in the Mapper interface cannot be overridden because they use the save and find strategy of the full name + method name. Mapper interface works by JDK dynamic proxy. Mybatis will use JDK dynamic proxy to generate a proxy object for Mapper interface. The proxy object will intercept the interface method and execute the SQL represented by MapperStatement. The SQL execution results are then returned.
How does Mybatis paginate? 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.
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.
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?
The first: DAO layer functions
public UserselectUser(String name,String area);
In the corresponding XML,#{0} represents the first parameter in the DAO layer,#{1} represents the second parameter in the DAO layer, and more parameters can be added later.
<select id="selectUser"resultMap="BaseResultMap">
select * fromuser_user_t whereuser_name = # {0}
anduser_area=# {1}
</select>Copy the code
Second: 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
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 written in Xml mapping file in the form of tag dynamic SQL, execution principle is based on the value of the expression to complete the logical judgment and dynamic splicing 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?
A:
,
, < SQL >,
, and
add nine tags for dynamic SQL, where < SQL > is the SQL fragment tag.
generates policy labels for primary keys that do not support auto-increment.
,
, and
add nine tags for dynamic SQL, where < SQL > is the SQL fragment tag.
generates policy labels for primary keys that do not support auto-increment.
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.
,>
. 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 for the Mapper interface methods are the same as those for each SQL parameterType defined in mapper.xml.
(3) The output parameter type of the Mapper interface method is the same as the type of each SQL resultType defined in mapper.xml;
(4) Namespace in mapper. XML file is the class path of Mapper interface.
26. What are the ways to write Mapper?
SqlSessionDaoSupport: To use this method, you need to write a mapper interface, mapper interface implementation class, mapper.xml file.
(1) Configure the mapper. XML location 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
(3) Implement class integration 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. If mapper. XML and mappre interface have the same name and are in the same directory, you do not need to configure mapper. XML
<mappers>
<mapper resource="Address of mapper. XML file" />
<mapper resource="Address of mapper. XML file" />
</mappers>Copy the code
(2) Define mapper interface:
(3) The namespace in mapper. XML is the address of the mapper interface
(4) The name of the method in the mapper interface must be the same as the ID of the statement defined in mapper. XML
(5) 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 implementation object of Mapper 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: Only ParameterHandler, ResultSetHandler, StatementHandler, and Executor interfaces can be used as plugins in Mybatis. The interface method interception function is implemented by generating proxy objects for the interface to be intercepted. Each of the four methods of the interface object is invoked, specifically the Invoke () method of InvocationHandler, which, of course, only intercepts those methods that you specify to be intercepted.
Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor (Mybatis) Interceptor
Welcome to my public account [Programmer Chase wind], 2019 many companies Java interview questions sorted out more than 120 pages of PDF documents, articles will be updated in it, sorted information will also be placed in it.
The last
Welcome everyone to exchange, like the article remember to pay attention to my like yo, thank you for your support!