In depth understanding of Mybatis configuration file

Posted by compt on Tue, 08 Mar 2022 20:53:15 +0100

1, Depth of Mybatis configuration file

1.1,SqlMapConfig.xml

Hierarchical relationship of Mybatis's core configuration file

Common configuration analysis of Mybatis

1. environments tab
Database environment configuration, supporting multi environment configuration

There are two types of transaction manager:

  • JDBC: this configuration directly uses JDBC's commit and rollback mechanism. It relies on the connection from the data source to manage the transaction scope.
  • MANAGED: this configuration never commits or rolls back a connection, but lets the container manage the entire life cycle of the transaction. By default, the connection will be closed automatically. Generally, the container does not want this. Therefore, you need to set the closeConnection property to false to prevent its default closing behavior.

There are three data sources:

  • UNPOOLED: the implementation of this data source only opens and closes the connection every time it is requested.
  • POOLED: this data source uses the concept of pool to encapsulate JDBC connection objects.
  • JNDI: this data source is implemented to be used in containers such as EJB or application server. The container can configure the data source externally and then place it in a JNDI context for reference.

2. mapper tag
The tag is loaded and mapped in the following ways:

  • Use a resource reference relative to the classpath, for example: com my. pojo. user
  • Use fully qualified resource locator (URL)
  • Use the mapping interface to implement the fully qualified class name of the class
  • Register all the mapper interface implementations in the package as mappers

3. properties tag

4. typeAliases label
Type alias is to set a short name for java objects, which is convenient to directly reference the short name in resultType
The mybatis framework has set some common type aliases for us:

1.2,mapper.xml

1.2.1 dynamic sql statement

In the mapping file of Mybatis, our sql is relatively simple. Sometimes when the business logic is complex, our sql changes dynamically. At this time, our sql can not meet the requirements in the previous study.

Dynamic sql

We use different sql statements to query according to different values of entity classes. For example, if the ID is not empty, we can query according to the ID. if the username is not empty, we also need to add the user name as a condition.

<select id="findByCondition" parameterType="user" resultType="user">
        select * from user
        <where>
            <if test="id!=0">
                and id = #{id}
            </if>
            <if test="username!=null">
                and username = #{username}
            </if>
        </where>
</select>

When both query condition id and username exist, the console prints the following statement:

// Get the UserMapper interface implementation class generated by mybatis framework
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
condition,setUsername("lucy");
User user = userMapper.findByCondition(condition);

When the condition query condition has only id, the console prints the sql statement:

// Get the UserMapper interface implementation class generated by mybatis framework
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
User user = userMapper.findByCondition(condition);

Dynamic sql

Execute sql splicing operation circularly

<select id="findByIds" parameterType="list" resultType="user">
     select * from User
     <where>
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
     </where>
</select>

The test code fragment is as follows:

//áž´ get the implementation class of UserMapper interface generated by mybatis framework
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int[] ids = new int[]{2,5};
List<User> userList = userMapper.findByIds(ids);
System.out.println(userList)

The attribute meaning of foreach tag is as follows:
The tag is used to traverse the collection

  • Collection: represents the collection elements to be traversed. Be careful not to write #{}
  • open: represents the beginning of the statement
  • close: represents the end of the statement
  • item: represents the variable name generated by traversing each element of the collection
  • sperator: represents the separator

SQL fragment extraction
Duplicate sql can be extracted from sql and referenced with include when used, so as to achieve the purpose of sql reuse

<!-- extract sql Fragment simplification -->
<sql id="selectUser" select * from User</sql>

<select id="findById" parameterType="int" resultType="user">
     <include refid="selectUser"></include> 
    where id=#{id}
</select>

<select id="findByIds" parameterType="list" resultType="user">
     <include refid="selectUser"></include>
 <where>
 <foreach collection="array" open="id in(" close=")" item="id"
separator=",">
 #{id}
 </foreach>
 </where>
</select>

Topics: Java Mybatis