Explain MyBatis in simple terms: all configurations of MyBatis

The last article introduced the related concepts of JDBC, the difference between the characteristics of MyBatis and Hibernate, the basic components and life cycle of MyBatis, and MyBatis can basically be used.

This article introduces the configuration of MyBatis in detail. First, look at the hierarchical structure of the configuration XML file, and then introduce each configuration item in detail, explaining the function of each item, the value and meaning of the value.

The hierarchical structure of the MyBatis configuration XML file is listed below. These levels cannot be reversed.

<?xml version="1.0" encoding="UTF-8"?>  
<configuration>  
    <properties/>  
    <settings/>  
    <typeAliases/>  
    <typeHandles/>  
    <objectFactory/>  
    <plugins/>  
    <environments>  
        <environment>  
            <transanctionManager/> <!-- 配置事务管理器 -->  
            <dataSource/> <!-- 配置数据源 -->  
        </environment>  
    </environments>  

    <databaseIdProvider/> <!-- 数据库厂商标识 -->  
    <mappers/> <!-- 映射器 -->  
</configuration>  

properties element

Declare some common and frequently changed values ​​separately and use it in the context of configuration files. MyBatis provides 3 configuration methods:

  • property child element
  • properties configuration file
  • Program parameter passing
property child element
    <properties>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mi-user"/>
        <property name="username" value="root"/>
        <property name="pwd" value="123456"/>
    </properties>
properties configuration file

Create a configuration file jdbc.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mi-user
username = root
password = 123456

Set properties configuration file

 <properties resource='jdbc.properties' />
Program parameter passing

In actual work, this scenario is encountered: the system is configured by the operation and maintenance personnel, the password of the generated database is kept secret from the developer, and the user name and password are encrypted. You can decrypt it first and then set the property by passing the program parameters.

//读入配置文件流
InputStream cfgStream = Resources.getResourceAsStream("mybatis-config.xml");
Reader cfgReader = new InputStreamReader(cfgStream);

//读入属性文件流
InputStream proStream = Resources.getResourceAsStream("jdbc.properties");
Reader proReader = new InputStreamReader(proStream);

Properties properties = new Properties();
properties.load(proReader);
//转换为明文
properties.setProperty("username",decode(properties.getProperty("username")));
properties.setProperty("pwd",decode(properties.getProperty("pwd")));

//创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(cfgReader,properties);

If three configurations appear at the same time, the priority is the third type > the second type > the first type, the second type is recommended, and the third type is used when there are special needs.

set up

The settings will change the behavior of MyBatis runtime. There are many settings, and only the commonly used configurations will be introduced. If you want to know all the configurations, you can check the official documentation.

  • cacheEnabled, which globally enables or disables any cache that has been configured by all mappers in the configuration file, the default is true;
  • lazyLoadingEnabled, a global switch for lazy loading. When enabled, all associated objects will be loaded lazily. In a specific relationship, the switch state of the item can be overridden by setting the fetchType property. The default value is false;
  • aggressiveLazyLoading, when enabled, any method call will load all properties of the object. Otherwise, each property will be loaded on demand, the default is true before version 3.4.1, and the default is false after 3.4.1;
  • autoMappingBehavior, specifies how MyBatis should automatically map columns to fields or attributes, NONE means cancel automatic mapping, PARTIAL will only automatically map result sets that do not define nested result set mapping, FULL will automatically map arbitrarily complex result sets, the default is PARTIAL;
  • autoMappingUnknownColumnBehavior, specifies the behavior of discovering the unknown column (or unknown attribute type) of the automatic mapping target, NONE: do nothing, WARNING: output a reminder log, FAILING: failed to map, the default is NONE;
  • defaultStatementTimeout, which sets the timeout, which determines the number of seconds the driver waits for a response from the database;
  • mapUnderscoreToCamelCase, whether to enable automatic camel case mapping, that is, a similar mapping from the classic database column name A_COLUMN to the classic Java attribute name aColumn, the default is false;
  • defaultEnumTypeHandler, specifies the default TypeHandler used by Enum, the default is org.apache.ibatis.type.EnumTypeHandler;
  • returnInstanceForEmptyRow, when all columns of the returned row are empty, MyBatis returns null by default. When this setting is turned on, MyBatis will return an empty instance, the default is false;
  • localCacheScope, MyBatis uses the local cache mechanism (Local Cache) to prevent circular references and speed up repeated nested queries. The default is SESSION, in which case all queries executed in a session are cached. If the setting value is STATEMENT, the local session is only used for statement execution, and different calls to the same SqlSession will not share data, the default is SESSION;
  • logImpl, specifies the specific implementation of the log, such as SLF4J|LOG4J|COMMONS_LOGGING, etc.;

alias

In the configuration mapping file, you need to specify the fully qualified name of the class. For simplicity, you can declare a short name to refer to it, which can be used in the MyBatis context. The system has defined common types for us, such as numeric values, strings, dates, sets, etc. For custom business POJOs, custom aliases are required.

<typeAliases>
     <typeAlias alias="role" type="com.learn.chapter2.po.Role"/>
</typeAliases>

It can also be done by annotation, first configure a scanned package, and then add the annotation @Alias("role") to the class definition.

<typeAliases>
     <package name="com.learn.chapter2.po" />
</typeAliases>
@Alias("role")
public class Role{
}

type handler

When MyBatis sets a parameter in a prepared statement or takes a value from the result set, it will use the registered typeHader for processing. The role of typeHander is to convert parameters from javaType to jdbcType, or convert jdbcType to javaType when retrieving the result from the database.

Commonly used type processors have been defined within the system, and in some cases, customization is required.

MyBatis also provides type handlers for enumeration types. There are 2 typeHandlers that convert enumeration types, EnumTypeHandler and EnumOrdinalTypeHandler, where EnumTypeHandler is passed using the enumeration string name as a parameter, and EnumOrdinalTypeHandler is passed using an integer subscript as a parameter .

However, these two enumeration types are not so widely used, and more often, custom typeHandlers are required for processing.

To customize a type handler, first define a type handler class and implement the TypeHandler generic interface:

public class SexEnumTypeHandler implements TypeHandler<Sex> {

    @Override
    public void setParameter(PreparedStatement ps, int i, Sex sex, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, sex.getId());
    }

    @Override
    public Sex getResult(ResultSet rs, String name) throws SQLException {
        return Sex.getSex(rs.getInt(name));
    }

    @Override
    public Sex getResult(ResultSet rs, int id) throws SQLException {
        return Sex.getSex(id);
    }

    @Override
    public Sex getResult(CallableStatement cs, int id) throws SQLException {
        return Sex.getSex(cs.getInt(id));
    }
}

Then register a custom TypeHandler

<typeHandlers>
   <typeHandler handler="com.qqdong.study.SexEnumTypeHandler" javaType="sex"/>
</typeHandlers>

Finally, when defining the mapper, specify the typeHandler

<select id="getUser" parameterType="long" resultType="userMap">
</select>

<resultMap id="userMap" type="user">
    <result column="sex" property="sex" typeHandler="com.qqdong.study.SexEnumTypeHandler">
</resultMap>

ObjectFactory

When MyBatis constructs a result and returns, it will use ObjectFactory to build POJO, and MyBatis can customize its own object factory. Generally, no configuration is required, just use the default DefaultObjectFactory.

plugin plugin

The plug-in is more complicated and will be introduced in a separate article later.

environmentsConfiguration environment

The configuration environment can register multiple data sources, and each data source includes basic configuration and database transaction configuration.

<environments default="development">
    <environment id="development">
    <!-- 采用jdbc事务管理 -->
        <transactionManager type="JDBC">
            <property name="autoCommit" value="false">
        </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>

Among them, transactionManager specifies database transactions, and there are 3 configuration methods:

  • JDBC, using JDBC to manage transactions, is often used in independent coding;
  • MANAGED, which manages transactions in a container mode, is commonly used in JNDI data sources;
  • Custom, user-defined database transaction management methods;

The dataSource tag configures the data source connection information, and the type configures the connection method to the database. There are the following types:

  • UNPOOLED: non-connection pool database;
  • POOLED: connection pool database;
  • JNDI: JNDI data source;
  • custom data source;

databaseIdProvider database vendor ID

The function of this property is to specify SQL to run in the database provided by the corresponding database vendor. It is not commonly used and will not be introduced.

mapper

The mapper is the most complex and core configuration of MyBatis, including parameter types, dynamic SQL, defined SQL, cached information and other functions. The previous article also demonstrated specific examples, and the next article will focus on details.

love story

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325216607&siteId=291194637
Recommended