MyBatis: configuration parsing

Configuration parsing

Core configuration file

  • mybatis-config.xml system kernel configuration file
  • MyBatis configuration file contains settings and properties that can deeply affect MyBatis behavior.
  • Content can be configured as follows:
configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
        environment(环境变量)
            transactionManager(事务管理器)
            dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
<!-- 注意元素节点的顺序!顺序不对会报错 -->

We can read mybatis-config.xml above dtd header files!

environments element

<environments default="development">
  <environment id="development"> <transactionManager type="JDBC"> <property name="..." value="..."/> </transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments>
  • MyBatis configuration several sets of operating environment, will be mapped to a plurality of different SQL databases, one of which must be specified (specified by default) as the default execution environment
  • Child element node: Environment

    • Specific set of environment, distinguished by setting id, id guaranteed to be unique!
    • Child element node: transactionManager - [Organizer]

      <!-- 语法 -->
      <transactionManager type="[ JDBC | MANAGED ]"/>
    • Child element node: a data source (the dataSource)

      • dataSource element using standard JDBC data source interface configured resource JDBC connection objects.
      • Data source must be configured.
      • There are three types of built-in data source

        type="[UNPOOLED|POOLED|JNDI]")
      • unpooled: opening and closing the connection to achieve this but each data source is requested.
      • the pooled : this data source is implemented using the concept of "cell" will organize JDBC connection objects, which is a popular Web application that concurrent processing request responsive manner.
      • jndi: This is to realize the data source can be used in such an application server, such as Spring or container, which may be centralized or configuration data in an external source, and then placing a reference JNDI context.
      • There are also many third-party data sources to achieve, such as dbcp, c3p0, druid and so on ....

mappers element

mappers

  • Mapper: custom mapping the SQL statement file
  • Since MyBatis behavior of other elements configured done, we're ready to define our mapped SQL statements. But first we need to tell MyBatis where to find them. Java automatically find in this area does not provide a good way, so the best way is to tell MyBatis where to find the map file. You can use the resource class path relative to a reference, or a fully qualified resource locator (including  file:/// in the URL), the class and package names, or the like. Mapper is one of the core components of MyBatis, before MyBatis 3, only supports xml mapper, namely: all SQL statements must be configured in the xml file. From the beginning MyBatis 3 also supports an interface mapper, mappers this way allows a Java code annotation defines SQL statement is very simple.

Introducing the way of resources

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/> </mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/> </mappers>
<!-- 
使用映射器接口实现类的完全限定类名
需要配置文件名称和接口名称一致,并且位于同一目录下
-->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/> </mappers>
<!-- 
将包内的映射器接口实现全部注册为映射器
但是需要配置文件名称和接口名称一致,并且位于同一目录下
-->
<mappers>
  <package name="org.mybatis.builder"/> </mappers>

Mapper file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.UserMapper"> </mapper>
  • namespace Chinese meaning: namespace role is as follows:

    1. id namespace and sub-elements of the joint guarantee a unique, distinguish between different mapper
    2. Binding DAO interface

      • namespace must be named with the same name as an interface
      • Methods and mapping file interface id in sql statement should correspond
    3. namespace naming rules: the package name + class name

The real power lies in its MyBatis mapping statement, which is its magic lies. Because of its extremely powerful, XML mapper file becomes relatively simple. If you take it compare with JDBC code with the same function, you will immediately find save nearly 95% of the code. MyBatis was built to focus on SQL, to reduce the hassle for you as possible.

Properties Optimization

These databases are externally configurable attributes and dynamically replaceable, may be arranged in a typical Java file attributes, sub-elements can also be transmitted by the properties element. Specific official documents

We optimize our configuration file

The first step; create a resource directory under db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root password=123456

Step two: the file into the configuration file properties

<configuration>
    <!--导入properties文件-->
    <properties resource="db.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>

More Actions, you can view the official document! [Presentation] led the study

  • Profiles priority issues
  • New Feature: Use placeholder

typeAliases optimization

Type an alias for Java type is set a short name. And only XML configuration related to the meaning of existence is only used to reduce redundancy fully qualified class name.

<!--配置别名,注意顺序-->
<typeAliases>
    <typeAlias type="com.kuang.pojo.User" alias="User"/> </typeAliases>

When so configured, Userit may be used in any com.kuang.pojo.Userplace.

You can also specify a package name, MyBatis will search package name below the required Java Bean, such as:

<typeAliases>
    <package name="com.kuang.pojo"/> </typeAliases>

Each package in the  com.kuang.pojo Java Bean in, in the absence of annotations, use the first letter lowercase Bean non-qualified class name as an alias for it.

If annotation is an alias for the annotation value. See the following example:

@Alias("user")
public class User { ... }

[Presentation] Quguan network look Mybatis default of some types of aliases!

Set up

  • Settings (settings) related => help documentation

    • Lazy loading
    • Log achieve
    • Cache On Off
  • An example of a fully configured settings following elements:

    <settings>
      <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="false"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="25"/> <setting name="defaultFetchSize" value="100"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="mapUnderscoreToCamelCase" value="false"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="OTHER"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> </settings>

Processor type

Official Documents

  • Whether a parameter is set in MyBatis prepared statement (the PreparedStatement) in the concentrator or retrieves a value from the result, it will be in a suitable manner to the Java type with the value of the acquired type of processor.
  • You can override the type of processor or create your own to deal with the type of processor does not support or non-standard types. [To understand]

Object Factory

Official Documents

  • Each time a new instance when MyBatis result object is created, it will use an object factory (ObjectFactory) instance to do so.
  • The default object factory needs to do is only an example of the target class, or by the default constructor, or instantiated by the constructor with a reference parameter map when present.
  • If you want to override the default behavior of the object factory, you can do so by creating your own object factory. [To understand]

Life Cycle and Scope

Scope (Scope) and life cycle

Understand the different scopes and lifecycles classes we already discussed is crucial, because incorrect use can lead to very serious concurrency issues.

We can first draw a flow chart, an analysis of the implementation process Mybatis!

1567006707407.png

Scope understand

  • After the role is to create SqlSessionFactoryBuilder SqlSessionFactory, create success, SqlSessionFactoryBuilder will lose its effect, so it can exist only way to create SqlSessionFactory in, but do not let a long time. Thus  preferred examples of the scope is a method SqlSessionFactoryBuilder scope (i.e. a local variable method).
  • SqlSessionFactory can be considered a database connection pool, its role is to create SqlSession interface objects. Because the essence of MyBatis is Java operation of the database, so SqlSessionFactory life cycle exists in the entire application MyBatis, so once the SqlSessionFactory creation, it is necessary to long-term preservation, until no longer use MyBatis application, it can be considered SqlSessionFactory life MyBatis period equivalent to the period of application.
  • Since SqlSessionFactory is a connection pool to the database, so it occupies a connection resource database. If you create multiple SqlSessionFactory, then there is more than one database connection pool, so that is not conducive to the control of database resources, will result in the database connection resources are depleted, the system downtime, etc. appear, so try to avoid this from happening.
  • So in general, we tend to want SqlSessionFactory application as a singleton, it is shared applications. So  the best SqlSessionFactory scope of application scope.
  • If SqlSessionFactory equivalent database connection pool, then SqlSession is equivalent to a database connection (Connection objects), you can execute multiple SQL in a single transaction, then it commit, rollback and other methods to commit or roll back the transaction. So it should survive in a service request, after processing the entire request, should be closed this connection, it returned to SqlSessionFactory, or database resources will soon be spent naked, the system will be paralyzed, so use try ... catch ... finally ... statement to ensure its proper close.
  • Therefore, the scope SqlSession best method is a request or scope.

1567007397555.png

Guess you like

Origin www.cnblogs.com/wpy188/p/12375452.html