MyBatis series (six): the use of the label if the MyBatis dynamic Sql

This blog mainly on how to use the label if generate dynamic Sql, mainly consists of the following three scenarios:

  1. Dynamic queries based on query
  2. The dynamic update some of the columns to achieve the parameter values
  3. Dynamic insertion parameter values ​​achieved according to some columns

1. if the label Dynamic Search

Assuming that there is such a demand: according to input conditions the user to query the user list, if you enter a user name, then the user name fuzzy query, if you enter a mailbox, on the precise queries based mailbox, if at the same time enter the user name and mailbox, you with these two conditions to match the user.

First, we add the following method in the interface SysUserMapper:

/**
 * 根据动态条件查询用户信息
 *
 * @param sysUser
 * @return
 */
List<SysUser> selectByUser(SysUser sysUser);

Then add the following code in the corresponding SysUserMapper.xml:

<select id="selectByUser" resultType="com.zwwhnly.mybatisaction.model.SysUser">
    SELECT  id,
            user_name,
            user_password,
            user_email,
            create_time
    FROM sys_user
    WHERE 1 = 1
    <if test="userName != null and userName != ''">
        AND user_name LIKE CONCAT('%',#{userName},'%')
    </if>
    <if test="userEmail != null and userEmail != ''">
        AND user_email = #{userEmail}
    </if>
</select>

The code is simple to explain:

1) test tag attribute if required, the attribute value is determined in line with a required expression OGNL, generally only a true or false result.

2) determination condition property! = Null or property == null, for any type of field, for determining whether the attribute value is null.

3) determination condition property! = '' Or property == '', only for type String field for determining whether an empty string.

4) When a plurality of determination conditions, and or or connection, can be determined using nested parentheses packet, and corresponds to the Java (&&), or associated with Java or (||).

Therefore, the above code means is to determine whether the field is null, then determine whether the field is an empty string.

Finally, add the following test method SysUserMapperTest test class:

@Test
public void testSelectByUser() {
    SqlSession sqlSession = getSqlSession();

    try {
        SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);

        // 只按用户名查询
        SysUser query = new SysUser();
        query.setUserName("ad");
        List<SysUser> sysUserList = sysUserMapper.selectByUser(query);
        Assert.assertTrue(sysUserList.size() > 0);

        // 只按邮箱查询
        query = new SysUser();
        query.setUserEmail("[email protected]");
        sysUserList = sysUserMapper.selectByUser(query);
        Assert.assertTrue(sysUserList.size() > 0);

        // 同时按用户民和邮箱查询
        query = new SysUser();
        query.setUserName("ad");
        query.setUserEmail("[email protected]");
        sysUserList = sysUserMapper.selectByUser(query);
        // 由于没有同时符合这两个条件的用户,因此查询结果数为0
        Assert.assertTrue(sysUserList.size() == 0);
    } finally {
        sqlSession.close();
    }
}

Run the test code, the test passes, outputting the log follows:

DEBUG [main] - ==> Preparing: SELECT id, user_name, user_password, user_email, create_time FROM sys_user WHERE 1 = 1 AND user_name LIKE CONCAT(’%’,?,’%’)

DEBUG [main] - ==> Parameters: ad(String)

TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time

TRACE [main] - <== Row: 1, admin, 123456, [email protected], 2019-06-27 18:21:07.0

DEBUG [main] - <== Total: 1

DEBUG [main] - ==> Preparing: SELECT id, user_name, user_password, user_email, create_time FROM sys_user WHERE 1 = 1 AND user_email = ?

DEBUG [main] - ==> Parameters: [email protected](String)

TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time

TRACE [main] - <== Row: 1001, test, 123456, [email protected], 2019-06-27 18:21:07.0

DEBUG [main] - <== Total: 1

DEBUG [main] - ==> Preparing: SELECT id, user_name, user_password, user_email, create_time FROM sys_user WHERE 1 = 1 AND user_name LIKE CONCAT(’%’,?,’%’) AND user_email = ?

DEBUG [main] - ==> Parameters: ad(String), [email protected](String)

DEBUG [main] - <== Total: 0

2. Use the tags if dynamic update

Suppose there is such a demand: when updating the user information field can not be updated, but that there is no change in value is empty or null, that is, only updating the value field.

First, we add the following method in the interface SysUserMapper:

/**
 * 根据主键选择性更新用户信息
 *
 * @param sysUser
 * @return
 */
int updateByIdSelective(SysUser sysUser);

Then add the following code in the corresponding SysUserMapper.xml:

<update id="updateByIdSelective">
    UPDATE sys_user
    SET
    <if test="userName != null and userName != ''">
        user_name = #{userName},
    </if>
    <if test="userPassword != null and userPassword != ''">
        user_password = #{userPassword},
    </if>
    <if test="userEmail != null and userEmail != ''">
        user_email = #{userEmail},
    </if>
    <if test="userInfo != null and userInfo != ''">
        user_info = #{userInfo},
    </if>
    <if test="headImg != null">
        head_img = #{headImg,jdbcType=BLOB},
    </if>
    <if test="createTime != null">
        create_time = #{createTime,jdbcType=TIMESTAMP},
    </if>
    id = #{id}
    WHERE id = #{id}
</update>

Finally, add the following test method SysUserMapperTest test class:

@Test
public void testUpdateByIdSelective() {
    SqlSession sqlSession = getSqlSession();

    try {
        SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);

        SysUser sysUser = new SysUser();
        // 更新id=1的用户
        sysUser.setId(1L);
        // 修改邮箱
        sysUser.setUserEmail("[email protected]");

        int result = sysUserMapper.updateByIdSelective(sysUser);
        Assert.assertEquals(1, result);

        // 查询id=1的用户
        sysUser = sysUserMapper.selectById(1L);
        // 修改后的名字保持不变,但是邮箱变成了新的
        Assert.assertEquals("admin", sysUser.getUserName());
        Assert.assertEquals("[email protected]", sysUser.getUserEmail());
    } finally {
        sqlSession.close();
    }
}

Run the test code, the test passes, outputting the log follows:

DEBUG [main] - ==> Preparing: UPDATE sys_user SET user_email = ?, id = ? WHERE id = ?

DEBUG [main] - ==> Parameters: [email protected](String), 1(Long), 1(Long)

DEBUG [main] - <== Updates: 1

DEBUG [main] - ==> Preparing: SELECT id, user_name, user_password, user_email, create_time FROM sys_user WHERE id = ?

DEBUG [main] - ==> Parameters: 1(Long)

TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time

TRACE [main] - <== Row: 1, admin, 123456, [email protected], 2019-06-27 18:21:07.0

DEBUG [main] - <== Total: 1

3. Insert if tag dynamic

Suppose there is such a demand: When inserting data into a database table, if the value of the parameter is not a column is empty, the passed value, if the incoming parameter is null, the default value in the database ( usually empty) instead passed a null value.

To better understand this example, we give user_email field is set to the default value sys_user table: test @ mybatis.tk, Sql statement is as follows:

ALTER TABLE sys_user
MODIFY COLUMN user_email VARCHAR(50) NULL DEFAULT  '[email protected]'
COMMENT '邮箱'
AFTER user_password;

First, we add the following method in the interface SysUserMapper:

/**
 * 根据传入的参数值动态插入列
 *
 * @param sysUser
 * @return
 */
int insertSelective(SysUser sysUser);

Then add the following code in the corresponding SysUserMapper.xml:

<insert id="insertSelective" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO sys_user(user_name, user_password,
    <if test="userEmail != null and userEmail != ''">
        user_email,
    </if>
    user_info, head_img, create_time)
    VALUES (#{userName},#{userPassword},
    <if test="userEmail != null and userEmail != ''">
        #{userEmail},
    </if>
    #{userInfo},#{headImg,jdbcType=BLOB},#{createTime,jdbcType=TIMESTAMP})
</insert>

Finally, add the following test method SysUserMapperTest test class:

@Test
public void testInsertSelective() {
    SqlSession sqlSession = getSqlSession();

    try {
        SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);

        SysUser sysUser = new SysUser();
        sysUser.setUserName("test-selective");
        sysUser.setUserPassword("123456");
        sysUser.setUserInfo("test info");
        sysUser.setCreateTime(new Date());

        sysUserMapper.insertSelective(sysUser);

        // 获取刚刚插入的数据
        sysUser = sysUserMapper.selectById(sysUser.getId());
        // 因为没有指定userEmail,所以用的是数据库的默认值
        Assert.assertEquals("[email protected]", sysUser.getUserEmail());
    } finally {
        sqlSession.close();
    }
}

Run the test code, the test passes, outputting the log follows:

DEBUG [main] - ==> Preparing: INSERT INTO sys_user(user_name, user_password, user_info, head_img, create_time) VALUES (?,?, ?,?,?)

DEBUG [main] - ==> Parameters: test-selective(String), 123456(String), test info(String), null, 2019-07-08 11:40:36.927(Timestamp)

DEBUG [main] - <== Updates: 1

DEBUG [main] - ==> Preparing: SELECT id, user_name, user_password, user_email, create_time FROM sys_user WHERE id = ?

DEBUG [main] - ==> Parameters: 1021(Long)

TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time

TRACE [main] - <== Row: 1021, test-selective, 123456, [email protected], 2019-07-08 11:40:37.0

DEBUG [main] - <== Total: 1

4. The reference source and

Source Address: https://github.com/zwwhnly/mybatis-action.git , welcome to download.

Liuzeng Hui "MyBatis from entry to the master."

The original is not easy, if that article can learn something, like a welcome point, a commentary on, off a note, this is my greatest motivation insist on writing.

If you are interested, please add my micro letter: zwwhnly , waiting for you to talk technology, workplace, work and other topics (PS: I am a programmer struggle in Shanghai).

Published 34 original articles · won praise 107 · views 20000 +

Guess you like

Origin blog.csdn.net/zwwhnly/article/details/103156350