MyBatis most comprehensive questions

1. # and $ difference

Configuration tab to perform query operations in the mapping file.
note:

  • {}: As a placeholder
    {id}: wherein id represents the name may be input parameters, if the name can be any simple type
  • $ {}: Sql statement indicates splicing
  • $ {Value}: indicates the name of the input parameters, if the parameters are simple types, the name of the parameter value must be

2, 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 a label, 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.
----------------
Disclaimer: This article is CSDN blogger original article "a745233700", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/a745233700/article/details/80977133

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

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

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.

5, Mybatis whether Enum can be mapped enumeration class?

Mybatis enumeration class can be mapped, it can be mapped not only enumerated classes, Mybatis any object can be mapped to a table. A custom mapping mode TypeHandler, achieve setParameter TypeHandler () and the getResult () interface method. TypeHandler has two functions, one is to complete the javaType jdbcType conversion is complete two to jdbcType javaType conversion method reflects the setParameter two () and the getResult (), representing the placeholder parameter set sql question mark and obtain column search result.

6, 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; after all namespace is not required, but the best practices it.
The reason is that namespace + id is as if there is no namespace, leaving id Map <String, MappedStatement> 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.

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

,,,,, dynamic sql plus nine tags, trim | where | set | foreach | if | choose | when | otherwise | bind the like, wherein the tag is a fragment sql, sql introduced through the label segments, do not support the self-energizing the primary key generation strategy labels.

8. Why Mybatis semi-automatic ORM mapping tools? Where it differs is in automatic?

Answer: Hibernate ORM is fully automatic mapping tools, the use of Hibernate query associated object or collection objects, can be directly obtained based on the object relational model, so 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.

9, the mapping between the brief Mybatis of Xml mapping file and Mybatis internal data structures?

A: Mybatis Xml all configuration information is encapsulated into All-In-One Configuration heavyweight objects inside. In Xml mapping file, the tag will be parsed as ParameterMap objects, each of its child elements are parsed as ParameterMapping object. ResultMap labels are parsed into objects, each sub-element will be parsed as ResultMapping object. Each ,,, tag will be parsed as MappedStatement objects, sql within the tag will be parsed as BoundSql object.

10, how Mybatis specify which one to use Executor executor?

A: Mybatis configuration file, you can specify the default ExecutorType actuator type, you can manually create a method to transfer ExecutorType SqlSession of DefaultSqlSessionFactory type parameters.

11, Mybatis what are the Executor executor? What is the difference between them?

A: Mybatis There are three basic Executor executor, SimpleExecutor, ReuseExecutor, BatchExecutor.

SimpleExecutor: Each time update or select, just open a Statement object, run out immediately closed Statement object.

ReuseExecutor: execute update or select, as a key to find sql Statement object exists on the use, it does not exist to create, after use, do not close the Statement object, but placed Map <String, Statement> within, for the next use. In short, re-use Statement objects.

BatchExecutor: execute update (not select, JDBC does not support batch select), all sql are added to the batch (addBatch ()), waiting for the uniform implementation (executeBatch ()), it caches multiple Statement objects, each Statement objects are addBatch () after completion, waiting for execution one by one executeBatch () batch. And JDBC same batch.

Scope: Executor of these features are strictly limited in scope SqlSession life cycle.

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

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

A: The first is to use the label, the mapping between the definition of column names one by one name and object properties
The second function is to use an alias sql column, the column alias name is written as object properties

14, Mybatis dynamic sql is doing what? What are dynamic sql? Can briefly principle of dynamic sql execution is not?

A: Mybatis dynamic sql can let us in Xml mapping file, write dynamic sql in the form of labels, complete logic and dynamic splicing sql functions, Mybatis offers nine dynamic sql tag trim | where | set | foreach | if | choose | when | otherwise | bind.

Principle of its execution, the value calculated from an expression using OGNL sql parameter object, according to the value of the dynamic splicing sql expression, in order to complete the function of dynamic sql

15, 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?

Answer: Dao interface is often said Mapper interface fully qualified name of the interface is the map file value namespace, and interface method name is the id mapping file MappedStatement values, parameters within the interface method is to transfer the parameters 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, may be a uniquely positioned MappedStatement, for example: com.mybatis3.mappers.StudentDao.findStudentById, can be found a unique namespace id = findStudentById com.mybatis3.mappers.StudentDao is below the MappedStatement. In Mybatis, each ,,, tag will be resolved to an MappedStatement object.

Dao in the interface method is not overloaded, because the policy is to preserve and to find the fully qualified name + method name.

Dao is the interface works JDK dynamic proxy will be used Mybatis running JDK dynamic proxy interface generation Dao proxy proxy object, the proxy object proxy intercepts interface methods in favor of the implementation of sql MappedStatement represented, then the sql execution results returned.

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

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

Disadvantage 18, MyBatis frame

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.

19, 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;

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.

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

21, 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.
Keywords: usegeneratedkeys, keyproperty
example:

<insert id=”insertname” *usegeneratedkeys*=true*keyproperty*=”id”>
      insert into names (name) values (#{name})
 </insert>

22, how to pass multiple parameters in a mapper in?

(1) a first: // Function Public UserselectUser DAO layer (String name, String Area);
(2) a second: Use @param annotation:
public interface UserMapper {
User selectuser (@param ( "username") String username, @ param ( "hashedpassword") String hashedpassword);
}
(. 3) third: a plurality of parameters encapsulated map

Released four original articles · won praise 0 · Views 36

Guess you like

Origin blog.csdn.net/Dream_V_v/article/details/105290313