[Turn] Mybatis common interview questions summary

1. What is Mybatis?

(1) Mybatis is a semi-ORM (object-relational mapping) framework that encapsulates the internal JDBC, SQL statements only need to focus on the development itself, does not need to spend energy to handle the loading drive, create a connection, create complicated process statement and so on. Programmers write directly to the original ecology sql, sql execution performance can be tightly controlled, high flexibility.

(2) MyBatis annotations may be using XML or native configuration and mapping information to map POJO database records, to avoid almost all JDBC code and manual setting parameters and obtaining the result set.

(3) various annotations or xml file statement by way of the configuration to be performed together, and the final map generation sql statement executed by a java objects and dynamic parameters of the sql statement, the last frame is performed by mybatis and mapping the result to sql java object and returns. (Process from the execution result returned to the sql).

2, Mybaits advantages:

(1) SQL statements based programming, is quite flexible and will not cause any impact on existing application or database design, SQL written in XML, decouple sql and program code, to facilitate unified management; providing XML tags, support the preparation of dynamic SQL statements can be reused.

(2) Compared with the JDBC, reducing the amount of code more than 50%, eliminating redundant code JDBC large, no manual switch is connected;

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

(4) can be well integrated with the Spring;

(5) provides a mapping label, field support ORM object-relational mapping database; providing an object-relational mapping label, object-relational component maintenance support.

3, MyBatis framework disadvantages:

Written work (1) SQL statement is large, especially when the field is more associated table for a long time, writing SQL statements for developer skills have certain requirements.

(2) SQL statement depends on the database, resulting in poor portability database, the database can not be replaced.

4, MyBatis framework applicable occasions:

(1) MyBatis focused on SQL itself, is a sufficiently flexible DAO layer solutions.

(2) high performance requirements, or more changes in project requirements, such as the Internet project, MyBatis would be a good choice.

 

5, MyBatis with Hibernate What are the differences?

Different (1) Mybatis and hibernate, it is not exactly an ORM framework, because MyBatis require programmers to write their own Sql statement.

(2) Mybatis write directly to the original ecology sql, sql execution can be tightly controlled performance, high flexibility, ideal for less demanding on the relational data model of software development, such software because of frequent changes in demand, but demand a change called for the speedy achievement output . But that flexibility can not be done on the premise that mybatis database-independent, if the need to implement the software supports multiple databases, you need a custom map file sets sql heavy workload. 

(3) Hibernate object / relational mapping capabilities strong, independent of the database is good for high-relational model requires software, if hibernate developers can save a lot of code and improve efficiency. 

 

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

# {} Is a pre-compiler process, $ {} string is replaced.

Mybatis when processing # {}, will be in sql number # {} with the call set assignment method PreparedStatement to?;

When processing Mybatis $ {}, {} $ is to replace the value of the variable.

Use # {} can effectively prevent SQL injection, improve system security.

 

7, when the field names in the entity class attribute name and the table is not the same, how do?

Unanimously adopted the definition of field names in the sql statement query aliases, so that the field name of the attribute name aliases and entity classes: the first kind.

    <SELECT ID = "selectorder" ParameterType = "int" = resultetype "me.gacl.domain.order">
SELECT ID order_id, order_no OrderNo, order_price. price order_id form Orders WHERE ID = # {};
</ SELECT>
second type : one to one mapping relationship entity class field names and attribute names by <resultMap>.

<SELECT ID = "getOrder" the parameterType = "int" The resultMap = "orderresultmap">
SELECT * WHERE Orders from order_id ID = # {}
</ SELECT>

<The resultMap type = "me.gacl.domain.order" ID = "orderresultmap ">
<! - with the id attribute to map the primary key field ->
<id property =" id "column =" order_id ">

<! - with the result attribute to map the non-primary key field, property of the entity class attribute names, column data table attributes ->
<property Result = "OrderNo" column = "order_no" />
<property Result = ". price" column = "order_price" />
</ reslutMap>
 

8, fuzzy query like how to write the statement?

Item 1: Adding sql wildcards in Java code.

wildcardname = String "SMI%%";
List <name> = mapper.selectlike names (wildcardname);

<SELECT ID = "selectlike">
SELECT * WHERE foo from bar like # {value}
</ SELECT>
2 species: sql statement stitching wildcard, it 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 a Xml mapping file, will write a corresponding interface to Dao, may I ask, what is the working principle of the interface is Dao? Dao interfaces in the methods, parameters are different, the method can reload it?

Dao interfaces namely Mapper interface. The fully qualified name of the interface, is the value of the mapping file of the namespace; interface method name, id value map is a file Mapper Statement; a parameter in the interface method, the parameter is passed to sql.

Mapper not interface implementation class, when a method call interface, the interface name + fully qualified method name as a string concatenation key value uniquely locating a MapperStatement. In Mybatis, each <select>, <insert>, <update>, <delete> tag is resolved to a MapperStatement object.

For example: com.mybatis3.mappers.StudentDao.findStudentById, you can find unique namespace for the com.mybatis3.mappers.StudentDao below the id findStudentById of MapperStatement.

Mapper interfaces in the method, is not overloaded, because it is using to save the fully qualified name + method name and look for strategies. Mapper interface that works JDK dynamic proxy, use JDK dynamic proxy objects proxy for the proxy interface generation Mapper, proxy objects will intercept interface methods in favor of the implementation of MapperStatement represented sql Mybatis run, sql execution then returns the results.

 

10, Mybatis how to page through? What is the principle pagination plug-in?

        Mybatis RowBounds objects using paging, it is for the memory paging ResultSet result set to perform, rather than the physical page. Parameter may be directly written with the physical pages in the physical page is accomplished sql function may be used to complete the physical page tab widget.

       The basic principle is to use the plug-in tab Mybatis plugin interface provided, to achieve a custom plug-ins, sql intercept interception to be performed within the insert method, and then rewrite the sql, according dialect dialect, add statements and physical page corresponding to the physical paging parameters.

 

11, Mybatis is how to execute sql package is the result of the target object and returns? What are mapping form?

The first is to use the <resultMap> tag, of defining the mapping between the attributes and object database column names.

The second function is to use an alias sql column, the column alias name is written as object properties.

Once you have a column mapping between names and attribute names, Mybatis creating objects through reflection, use reflection individually assigned to the properties of the object and returns, those properties can not find the mapping relationship, it is unable to complete the assignment.

 

12, how to perform bulk insert?

First, create a simple insert statement:

<INSERT ID = "insertname">
    INSERT INTO names (name) values (# {value})
</ INSERT>
then execute the following batch inserted like this java code:

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 (master) key?

int insert method always returns a value that represents the number of rows inserted.

If self-growth strategy, automatically generated key in the insert after the implementation of the method can be set to the passed parameter object.

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 a mapper in?

(1) a first:
// function DAO layer
Public UserselectUser (String name, String Area); 
// corresponding xml, # {0} is the first representative of the received parameter dao layer, {# 1} dao parameter representative of a second layer, more parameters can be added later consistent.
<SELECT ID = "selectUser" The resultMap = "BaseResultMap"> 
SELECT * fromuser_user_t whereuser_name = {0} # = # {anduser_area. 1} 
</ SELECT> 

(2) The second: Use @param annotation:
public interface UserMapper {
User selectuser (@param ( "username") String username, @ param ( "hashedpassword") String hashedpassword);
}
can then be used as such in the xml as follows (the recommended package of a map, is 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) Third: a plurality of parameters encapsulated Map
the try {
// .SQL ID namespace segment mapping file, you can call the corresponding mapping file in the SQL
// Since our more than two parameters, and the method of collecting only an Object argument, so we use our Map to load parameter set
Map <String, Object> = new new Map the HashMap ();
map.put ( "Start", Start);
map.put ( "End", End);
return sqlSession.selectList ( "StudentID.pagination", Map);
} the catch (Exception E) {
e.printStackTrace ();
sqlSession.rollback ();
the throw E;}
the finally {
MybatisUtil.closeSqlSession ();
}
 

15, Mybatis dynamic sql what's the use? The implementation of the principle? What we have dynamic sql?

Mybatis dynamic sql Xml may be in the map file prepared in the form of dynamic sql tag, execution is complete logical judgment principle and functions according to the dynamic mosaic sql value of the expression.

Mybatis offers nine kinds of dynamic sql Tags: trim | where | set | foreach | if | choose | when | otherwise | bind.

 

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

A: <resultMap>, <parameterMap>, <sql>, <include>, <selectKey>, together with the dynamic label sql 9, wherein <sql> tag of sql fragments, fragments introduced sql <include> tags, < selectKey> tag generation strategy that does not support auto-incrementing primary key.

 

17, Mybatis of Xml mapping file, different Xml mapping file, id if you can repeat?

Different Xml mapping file, if a configuration namespace, then the id can be repeated; if there is no namespace configured, id can not be repeated;

The reason is that namespace + id is as if there is no namespace, leaving id Map <String, MapperStatement> use the key, then, id will lead to duplicate data overwrite each other. With namespace, natural id can be repeated, different namespace, namespace + id naturally different.

 

18, why Mybatis semi-automatic ORM mapping tools? Where it differs is in automatic?

Hibernate ORM mapping tool is fully automatic, with the Hibernate query associated object or collection object can be directly obtained according to an object-relational model, it is fully automatic. And Mybatis when querying the associated object or collection of objects associated with the need to manually write sql to complete, so called semi-automatic ORM mapping tools.

 

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

<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 "/> <-! Collection-many associated with the query -> </ resultMap> 
</ Association or> 




<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, MyBatis There are several ways to achieve one? Specifically how to operate?

And has joint inquiry nested query, the query is combined several tables joint inquiry, inquiry only once, by arranging resultMap node association configuration inside one of the classes can be completed;

Nested query is to check a table, according to the results of the foreign key table id inside, and then further to a table inside the data query, but also by association configuration, but another table through a select attribute query configuration.

 

21, MyBatis There are many ways to achieve, how to operate?

        There are joint inquiry and nested queries. Combined query tables several joint inquiry, inquiry only once by arranging many classes resultMap inside the collection node can be completed; nested query is a table to check, the results of the table inside the foreign key id, Still further to a table inside the data query, but also by arranging Collection, but additionally by a look-up table select node configuration.

 

22, Mybatis support lazy loading? If so, what is its principle is to achieve?

A: Mybatis association only supports lazy loading the associated object collection and a collection of associated objects, association refers to one, collection refers to the many queries. In Mybatis configuration file, you can configure whether to enable lazy loading lazyLoadingEnabled = true | false.

Its principle is to use CGLIB create a proxy object of the target object when the target method call, enter the interceptor methods, such as call a.getB (). GetName (), interceptor invoke () method found a.getB () is null value, then it will separate the saved queries sent in advance sql associated object B, the query up B, then call a.setB (b), then there is a target attribute value b, and then completed a.getB ( ) call .getName () method. This is the basic principle lazy loading.

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

 

 23, Mybatis primary, secondary cache:

1) a cache: a HashMap based PerpetualCache local cache, which stores a scope of Session, Session after the flush or close, all of the Cache will be emptied in the Session, by default cache.

2) a secondary cache and cache the same mechanism, but also using default PerpetualCache, HashMap stored, it is stored in a different scope as Mapper (Namespace), and may be custom storage source, such as Ehcache. The default secondary cache is not opened, to open the secondary cache, the secondary cache using the properties required to implement the Serializable class serialization interface (used to save the state of the object), it may be disposed on mapping file <cache />;

3) For data cache update mechanism, when performing the C / U / D operation of a certain scope (a cache Session / secondary cache the Namespaces) after default select the scope of all the cache will be clear.

 

24, what is the interface binding of MyBatis? What implementations?

Interface binding, is arbitrarily defined interface MyBatis, and then the inside of the interface methods SQL statements and bind, we can directly call the interface methods, so compared to the original method SqlSession provided we can have a more flexible options and settings .

Interface binding implemented in two ways, one is through binding annotations, it is to add @ Select, @ Update and other annotation, which contains the interface Sql statement in the above method to bind; another is to write SQL by xml inside to bind, in this case, to specify the xml mapping file inside the namespace must be a full path name of the interface. When Sql statement is simple when using binding annotations, when more complex SQL statements when using xml binding, usually with xml binding more.

25, which requires the use of MyBatis mapper interface call?

① id of each sql Mapper names and interface methods defined in the same mapper.xml;
same type parameterType sql each input parameter type and mapper.xml ② Mapper interface methods defined;
output parameter type interface method ③ Mapper sql same type and each resultType mapper.xml defined;
④ Mapper.xml file namespace i.e. classpath mapper interface.

26, Mapper, which has several ways to write?

The first: the interface class inheritance SqlSessionDaoSupport: Use this method need to write an interface mapper, mapper interface class, mapper.xml file.
(1) arranged in a position mapper.xml sqlMapConfig.xml the
<by mappers>
    <Resource Mapper = "address mapper.xml file" />
    <Resource Mapper = "address mapper.xml file" />
</ by mappers>
( 2) define an interface mapper
(3) integrated implementation class SqlSessionDaoSupport
mapper process data can be CRUD this.getSqlSession ().
(4) spring configuration
<bean id = "" class = " mapper interface implemented">
    <Property name = "SqlSessionFactory" REF = "SqlSessionFactory"> </ Property>
</ the bean>

 
The second: Use org.mybatis.spring.mapper.MapperFactoryBean:
(. 1) arranged in a position mapper.xml sqlMapConfig.xml, the same if the name and mappre mapper.xml and interfaces in the same directory, there can not configure
<by mappers>
    <mapper Resource = "address mapper.xml file" />
    <mapper Resource = "address mapper.xml file" />
</ by mappers>
(2) defines an interface mapper:
①mapper.xml mapper is in namespace address of the interface
statement of id ②mapper interface and the method name defined in mapper.xml consistent
defined ③Spring
<the bean ID = "" class = "org.mybatis.spring.mapper.MapperFactoryBean">
    <Property name = "mapperInterface "value =" mapper interface address "/> 
    <Property name =" SqlSessionFactory "REF =" SqlSessionFactory "/> 
</ the bean>


Third: Use mapper scanner:
preparation of (1) mapper.xml file:
mapper.xml the namespace address mapper interface;
Statement of mapper interface and method names defined in mapper.xml consistent id;
if the mapper.xml and mapper name of the interface is consistent in not configured in sqlMapConfig.xml. 
(2) define an interface mapper:
Note mapper.xml the interface name and the file name mapper consistent, and the same directory
(3) of the mapper Scanner:
<the bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" >
    <Property name = "basePackage" value = "Mapper interface packet address"> </ Property>
    <Property name = "sqlSessionFactoryBeanName" value = "SqlSessionFactory" /> 
</ the bean>
(. 4) using the scanner after the vessel from the spring Gets an object that implements the mapper.

 

27, operating principles outlined Mybatis plug-ins, as well as how to write a plugin.

A: Mybatis only be written for ParameterHandler, ResultSetHandler, StatementHandler, Executor of these four plug-in interface, Mybatis use JDK dynamic proxy for the proxy object interface generation need to intercept interface methods to achieve blocking feature, whenever the implementation of the four interfaces when the method of the object, will enter the intercept method, the concrete is InvocationHandler invoke () method, of course, you will only need to intercept those you specify interception.

Writing Plugins: Mybatis achieve the Interceptor interfaces and replication intercept () method, and then write notes to the plug-in, specify which interface to which methods to intercept, remember, do not forget to write your configuration in the configuration file plugin.
--------------------- 
Author: a745233700 
Source: CSDN 
Original: https: //blog.csdn.net/a745233700/article/details/80977133 

Guess you like

Origin www.cnblogs.com/gaobing1252/p/11110657.html