MyBatis can be used in JDBC, Hibernate and MyBatis. MyBatis can be used in JDBC.

Article Index:

  1. Introduction to JDBC and MyBatis
  2. All configurations of MyBatis
  3. Mapper knows all about it

This article introduces the configuration of MyBatis in detail, first look at the configuration XML file hierarchy, and then introduce each configuration item in detail, explain the role of each item, the value of the value and meaning.

The hierarchy of the MyBatis configuration XML file is listed below and cannot be reversed.

<?xml version="1.0" encoding="UTF-8"? >  
<configuration>  
    <properties/>  
    <settings/>  
    <typeAliases/>  
    <typeHandles/>  
    <objectFactory/>  
    <plugins/>  
    <environments>  
        <environment>  
            <transanctionManager/> <! -- Configure transaction manager -->  
            <dataSource/> <! -- Configure data source -->  
        </environment>  
    </environments>  
  
    <databaseIdProvider/> <! -- Database vendor id -->  
    <mappers/> <! -- Mapper -->  
</configuration>  
Copy the code

The properties element

To declare some common, frequently changed values separately, you can use them in the context of a configuration file. MyBatis provides three configurations:

  • The property child elements
  • Properties configuration file
  • Program parameter passing
The property child elements
    <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>
Copy the code
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
Copy the code

Set up the Properties profile

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

In practice, the system is configured by operation and maintenance personnel, and the password of the database generated is confidential to the developer, and the user name and password are encrypted. Property can be decrypted by passing program parameters.

 // Read the configuration file stream
InputStream cfgStream = Resources.getResourceAsStream("mybatis-config.xml");
Reader cfgReader = new InputStreamReader(cfgStream);

// Read the properties file stream
InputStream proStream = Resources.getResourceAsStream("jdbc.properties");
Reader proReader = new InputStreamReader(proStream);

Properties properties = new Properties();
properties.load(proReader);
// Convert to plaintext
properties.setProperty("username",decode(properties.getProperty("username")));
properties.setProperty("pwd",decode(properties.getProperty("pwd")));

/ / create a sqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(cfgReader,properties);
Copy the code

If the three configurations occur at the same time, the priority is 3 > 2 > 1. The second configuration is recommended. The third configuration is recommended for special requirements.

Set up the

Settings will change the behavior of MyBatis runtime. There are many Settings, only common configurations will be introduced. For details about all configurations, please check the official documentation.

  • CacheEnabled, which globally turns on or off any caches that have been configured by all mappers in a configuration file, defaults to true;
  • LazyLoadingEnabled: Global lazy loading switch. When enabled, all associated objects will be lazy loaded. In a specific association, you can set the fetchType attribute to override the status of the global lazy loading switch.
  • Aggressive Azyloading, when turned on, a call to any method loads all of the properties of that object. Otherwise, each attribute is loaded on demand, which defaults to true prior to 3.4.1 and false after 3.4.1;
  • AutoMappingBehavior specifies how MyBatis should automatically map columns to fields or attributes. NONE indicates that automatic mapping is disabled. PARTIAL only automatically maps results that do not have nested result sets mapped.
  • AutoMappingUnknownColumnBehavior, specify found automatically map the target unknown column (or unknown attribute types), NONE: don’t do any response, WARNING: remind log output, FAILING: mapping failure, default to NONE;
  • DefaultStatementTimeout, which sets the timeout time, which determines the number of seconds the driver waits for a database response;
  • MapUnderscoreToCamelCase: specifies whether to enable CamelCase mapping, that is, a similar mapping from the classic database column name A_COLUMN to the classic Java attribute name aColumn. The default value is false.
  • Use default TypeHandler defaultEnumTypeHandler, specified Enum, default is org. Apache. Ibatis. The EnumTypeHandler;
  • ReturnInstanceForEmptyRow, when rows returned all columns are empty, MyBatis returns null by default. When enabled, MyBatis returns an empty instance, false by default;
  • LocalCacheScope, MyBatis uses Local Cache mechanism to prevent circular references and accelerate repeated nested queries. The default value is SESSION, in which case all queries executed in a SESSION are cached. If the value is set to STATEMENT, the local SESSION is only used for STATEMENT execution. Different calls to the same SqlSession do not share data. SESSION is used by default.
  • LogImpl, specify the log concrete implementation, such as SLF4J | LOG4J | COMMONS_LOGGING etc.

The 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 values, strings, dates, collections, and so on. For custom business POJOs, custom aliases are required.

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

You can also annotate by first configuring a scanned package and then adding an annotation @alias (“role”) to the class definition.

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

Type processor

When MyBatis sets a parameter in a preprocessed statement, or extracts a value from the result set, it will use the registered typeHader to handle it. TypeHander simply converts parameters from javaType to jdbcType, or jdbcType to javaType when the result is fetched from the database.

Common type handlers are already defined internally and, in some cases, custom.

MyBatis also provides type handlers for enumeration types. There are two typeHandlers that convert enumeration types, EnumTypeHandler and EnumOrdinalTypeHandler, where EnumTypeHandler is passed with enumeration string names as arguments. EnumOrdinalTypeHandler is passed with integer subscripts as arguments.

However, these two enumerated types are less widely used and more often require custom typeHandler processing.

To define a custom TypeHandler, we begin by defining a type-handling class that implements 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 {
        returnSex.getSex(cs.getInt(id)); }}Copy the code

Then register your custom TypeHandler

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

Finally, when defining the mapper, you simply specify 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>
Copy the code

ObjectFactory

When MyBatis builds a result, it will use ObjectFactory to build pojos. You can customize your own ObjectFactory in MyBatis. Do not use the default DefaultObjectFactory.

Plug-in plugin

Plug-ins are complicated and will be covered in a separate article.

Environments configuration environment

The configuration environment can register multiple data sources, each including base configuration and database transaction configuration.

<environments default="development">
    <environment id="development">
    <! JDBC transaction management -->
        <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>
Copy the code

TransactionManager specifies database transactions, which can be configured in three ways:

  • JDBC, which uses JDBC to manage transactions, is often used in independent coding;
  • MANAGED, a container for managing transactions, is commonly used in JNDI data sources;
  • Customization, by the user to define the database transaction management method;

The dataSource tag configures the dataSource connection information. Type configures the database connection mode.

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

DatabaseIdProvider Indicates the vendor id of the database

The purpose of this property is to specify the SQL to run in the database provided by the corresponding database vendor. If you don’t use it often, I won’t introduce it.

mapper

Mapper is the most complex and core configuration of MyBatis, including parameter type, dynamic SQL, define SQL, cache information and other functions, the last article also demonstrated specific examples, the next article will focus on details.

Please scan the qr code below and follow my personal wechat official account ~