[MyBatis Series 1] Basics

It mainly explains the basic knowledge of MyBatis, and the content comes from C language Chinese network.

MyBatis example

Project preparation

The DB uses Mysql, POM Dependency packages to be added to XML:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

DB structure:

CREATE TABLE `user_test` (
  `uid` tinyint(2) NOT NULL,
  `uname` varchar(20) DEFAULT NULL,
  `usex` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

DB initial data:

uidunameusex
1Zhang Sanfemale
2Chen Hengmale
3Lou Zimale

Specific examples

Step 1: create a persistence class first:

@Data
public class MyUser {
    private Integer uid; //Primary key
    private String uname;
    private String usex;
}

Step 2: create a mapping 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.mybatis.dao.UserDao">
    <!-- according to uid Query a user information -->
    <select id="selectUserById" parameterType="Integer" resultType="com.mybatis.entity.MyUser">
        select * from user_test where uid = #{uid}
    </select>
    <!-- Query all user information -->
    <select id="selectAllUser" resultType="com.mybatis.entity.MyUser">
        select * from user_test
    </select>
    <!-- Add a user,#{uname} is com mybatis. po. Attribute value of myuser -- >
    <insert id="addUser" parameterType="com.mybatis.entity.MyUser">
        insert into user_test (uid,uname,usex)
        values(#{uid},#{uname},#{usex})
    </insert>
    <!--Modify a user -->
    <update id="updateUser" parameterType="com.mybatis.entity.MyUser">
        update user_test set uname =#{uname},usex = #{usex} where uid = #{uid}
    </update>
    <!-- Delete a user -->
    <delete id="deleteUser" parameterType="Integer">
        delete from user_test where uid= #{uid}
    </delete>
</mapper>

Step 3: create MyBatis configuration file

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J" />
        <setting name="cacheEnabled" value="false"/>
        <setting name="defaultExecutorType" value="REUSE"/>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <!-- to configure mybatis Operating environment -->
    <!-- If only start mybatis,It must be needed here; If passed spring use mybatis,You can delete it here because SQL Configuration of src/main/resources/applicationContext.xml in -->
    <environments default="development">
        <environment id="development">
            <!-- use JDBC Transaction management -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- MySQL Database driven -->
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <!-- Connecting to the database URL -->
                <property name="url" value="jdbc:mysql://xxx:xxx/xm_jointly?characterEncoding=utf8" />
                <property name="username" value="jointly_xxx" />
                <property name="password" value="G-uTlU-xxx" />
            </dataSource>
        </environment>
    </environments>
<!--     take mapper Add file to configuration file-->
    <mappers>
        <mapper resource="com/mybatis/mapper/UserMapper.xml" />
    </mappers>
</configuration>

Step 4: create a test class

public class MyBatisTest {
    public static void main(String[] args) {
        try {
            //Read the configuration file mybatis config xml
            InputStream config = Resources.getResourceAsStream("com/mybatis/config/datasources/mybatis-config.xml");
            //Build SqlSessionFactory from configuration file
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
            //Create SqlSession through SqlSessionFactory
            SqlSession ss = ssf.openSession();

            //Query a user
            MyUser mu = ss.selectOne("com.mybatis.dao.UserDao.selectUserById", 1);
            System.out.println(mu);

            //Modify a user
            MyUser updatemu = new MyUser();
            updatemu.setUid(1);
            updatemu.setUname("Zhang San");
            updatemu.setUsex("female");
            ss.update("com.mybatis.dao.UserDao.updateUser", updatemu);

            //Query all users
            List<MyUser> listMu = ss.selectList("com.mybatis.dao.UserDao.selectAllUser");
            for (MyUser myUser : listMu) {
                System.out.println(myUser);
            }
            //Commit transaction
            ss.commit();
            //Close SqlSession
            ss.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output:

MyUser(uid=1, uname=Zhang San, usex=female)
MyUser(uid=1, uname=Zhang San, usex=female)
MyUser(uid=2, uname=Chen Heng, usex=male)
MyUser(uid=3, uname=Lou Zi, usex=male)

Overall structure of the project:

Detailed description of configuration file

The MyBatis configuration file is not complex. All its elements are as follows:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- to configure -->
    <properties /><!-- attribute -->
    <settings /><!-- set up -->
    <typeAliases /><!-- Type naming -->
    <typeHandlers /><!-- Type processor -->
    <objectFactory /><!-- Object factory -->
    <plugins /><!-- plug-in unit -->
    <environments><!-- Configuration environment -->
        <environment><!-- environment variable -->
            <transactionManager /><!-- Transaction manager -->
            <dataSource /><!-- data source -->
        </environment>
    </environments>
    <databaseIdProvider /><!-- Database vendor identification -->
    <mappers /><!-- Mapper -->
</configuration>

However, it should be noted that the order of MyBatis configuration items cannot be reversed. If their order is reversed, an exception will occur during MyBatis startup, resulting in the program being unable to run.

properties

The properties property can configure some operating parameters for the system, which can be placed in XML files or properties files instead of Java coding. The advantage is that it is convenient to modify parameters without causing code recompilation. Generally speaking, MyBatis provides three ways for us to use properties. They are property child elements, property files and program code transmission. Here we only talk about the way of "property child elements".

Based on the following code, use the property sub element to rewrite the relevant configuration of the database connection. Here, you can directly refer to the XML configuration in the "MyBatis example".

Here, the child element "property" under the element "properties" is used to define, using the string database Username defines the database user name, and then you can introduce this defined attribute parameter into the database definition, such as ${database.username}, so that it can be referenced everywhere once defined. However, if there are hundreds of attribute parameters, it is obviously not a good choice to use this method. At this time, you can use the properties file.

properties file, which is very simple. It mainly puts the relevant configuration information of Mysql into XX properties, which will be introduced later when the integration of MyBatis and Spring is described.

settings

In MyBatis, settings is the most complex configuration. It can deeply affect the underlying operation of MyBatis. However, in most cases, it can be run by using the default value. Therefore, in most cases, it does not need to be configured in large quantities. It only needs to modify some common rules, such as automatic mapping, hump naming mapping, cascade rules, whether to start caching Type of actuator, etc.

There are many configuration items in settings, but not many are really used. We can study the common configuration items clearly, such as cacheEnabled for cache, lazyloading enabled and aggregatelazy loading for cascade, autoMappingBehavior and mapUnderscoreToCamelCase for automatic mapping, defaultExecutorType for actuator type, etc.

There are too many things. I won't look at them one by one. Just pick a few key ones.

typeAliases

Because the fully qualified name of a class is very long, it is inconvenient to always write such a long name when it needs to be used a lot. In MyBatis, it is allowed to define a short name to represent this class, which is alias. Alias is divided into system defined alias and user-defined alias. In MyBatis, aliases are defined by the class TypeAliasRegistry (org.apache.ibatis.type.TypeAliasRegistry). Note that aliases are not case sensitive in MyBatis.

I don't think this one is used much. I won't know it in detail first. When I need it, I'll come back and have a look.

typeHandlers

In JDBC, you need to set the parameters of those precompiled SQL statements in the PreparedStatement object. After executing SQL, the database data will be obtained through the ResultSet object, and these MyBatis are implemented through typeHandler according to the data type.

typeHandler is divided into jdbcType and javaType. jdbcType is used to define database type and javaType is used to define Java type. The role of typeHandler is to undertake the mutual conversion between jdbcType and javaType. In many cases, we do not need to configure typeHandler, JDBC type and javaType, because MyBatis will detect what type of typeHandler should be used for processing, but some scenarios cannot be detected. For those scenarios where user-defined enumeration is required, or where the database uses special data types, you can use a user-defined typeHandler to handle the conversion between types.

The typeHandler provided by the system can cover the requirements of most scenarios, but it is not enough in some cases. For example, we have special conversion rules, such as enumeration classes.

Like typeAliases, this one is not used much. Don't learn more about it first, leave a record, and come back if necessary.

objectFactory

When creating a result set, MyBatis uses an object factory to create the result set instance. By default, MyBatis will use its defined object factory, DefaultObjectFactory (org.apache.ibatis.reflection.factory.DefaultObjectFactory), to complete the corresponding work.

MyBatis allows you to register custom objectfactories. If customized, you need to implement the interface org apache. ibatis. reflection. factory. ObjectFactory and configure it.

In most cases, we do not need to customize the return rules because these are complex and error prone. In more cases, we will consider inheriting the DefaultObjectFactory already implemented by the system and complete the work we need through certain rewriting.

Just to understand, because we generally do not create our own "object factory".

environments

In MyBatis, the main function of the running environment is to configure database information. It can configure multiple databases. Generally speaking, only one of them needs to be configured. It is divided into two configurable elements: transaction manager and data source. Let's go back to the configuration in our example

<environments default="development">
    <environment id="development">
        <!-- use JDBC Transaction management -->
        <transactionManager type="JDBC" />
        <dataSource type="POOLED">
            <!-- MySQL Database driven -->
            <property name="driver" value="com.mysql.jdbc.Driver" />
            <!-- Connecting to the database URL -->
            <property name="url" value="jdbc:mysql://xxx:xxx/xm_jointly?characterEncoding=utf8" />
            <property name="username" value="jointly_xxx" />
            <property name="password" value="G-uTlU-xxx" />
        </dataSource>
    </environment>
</environments>

In the actual work, Spring will be used to manage the transactions of data sources and databases in most cases. This will be explained in the next article "integration of Spring and MyBatis".

transactionManager

In MyBatis, transactionManager provides two implementation classes. It needs to implement the interface transaction (org.apache.ibatis.transaction.Transaction). Its definition code is as follows.

public interface Transaction {
    Connection getConnection() throws SQLException;
    void commit() throws SQLException;
    void rollback() throws SQLException;
    void close() throws SQLException;
    Integer getTimeout() throws SQLException;
}

It can be seen from the method that its main work is to commit, rollback and close the transactions of the database. MyBatis provides two implementation classes for Transaction: JdbcTransaction and ManagedTransaction, as shown in Figure 1.

Therefore, it corresponds to two factories: JdbcTransactionFactory and ManagedTransactionFactory. This factory needs to implement the TransactionFactory interface, through which the corresponding Transaction object will be generated. Therefore, the Transaction manager can be configured in the following two ways:

<transactionManager type="JDBC"/>
<transactionManager type="MANAGED"/>

Here is a brief description:

  • JDBC is implemented using the JdbcTransaction object generated by the JdbcTransactionFactory. It operates the submission and rollback of the database in the way of JDBC.

  • MANAGED is implemented using the ManagedTransaction object generated by ManagedTransactionFactory. Its commit and rollback methods do not need any operation, but hand over the transaction to the container for processing. By default, it closes the connection, but some containers do not want this, so you need to set the closeConnection property to false to prevent its default closing behavior.

Of course, you can also define your own transaction manager, which will not be expanded here.

environment

environment is mainly used to configure the database. In MyBatis, the database is provided through PooledDataSource Factory, UnpooledDataSourceFactory and JndiDataSourceFactory. The first two generate PooledDataSource and UnpooledDataSource class objects, JndiDataSourceFactory will get the database connection object implemented by the external container according to the JNDI information.

Regardless of the three factory classes, the final generated product will be a database connection object that implements the DataSource interface. Since there are three data sources, they can be configured as follows.

<dataSource type="UNPOOLED">
<dataSource type="POOLED">
<dataSource type="JNDI">

Discuss these three data sources and their attributes:

  • UNPOOLED: UNPOOLED adopts the management mode of non database pool. Each request will open a new database connection, so the creation will be slow. It can be used in some occasions where there is no high demand for performance.

  • POOLED: the data source POOLED uses the concept of "pool" to organize JDBC Connection objects. At first, there will be some vacant and connected database connections. Therefore, there is no need to establish and verify when requesting, and the initialization and authentication time necessary to create a new Connection instance is saved. It also controls the maximum number of connections to avoid system bottlenecks caused by too many connections.

  • JNDI: data source JNDI is implemented to be used in containers such as EJB or application server. The container can centrally or externally configure the data source, and then place a reference to the JNDI context.

Welcome to the many more articles, please pay attention to the official account of WeChat public, "the road of Lou Tsai", pay attention to it and not lose your way.

Keywords: Mybatis

Added by msaspence on Wed, 05 Jan 2022 05:37:42 +0200