Usage choose MyBatis dynamic Sql it, where, set the label: MyBatis series (seven)

This blog mainly on how to use choose, where, set label generation dynamic Sql.

1. choose Usage

Assuming that there is such a demand: when the id parameter value has precedence id query, when there is no id value went to determine whether the user name has value, if there is a value to the query with a user name, if no values, it makes no inquiry result .

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

/**
 * 根据用户id或用户名查询
 *
 * @param sysUser
 * @return
 */
SysUser selectByIdOrUserName(SysUser sysUser);

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

<select id="selectByIdOrUserName" resultType="com.zwwhnly.mybatisaction.model.SysUser">
    SELECT  id,
            user_name,
            user_password,
            user_email,
            create_time
    FROM sys_user
    WHERE 1 = 1
    <choose>
        <when test="id != null">
            AND id = #{id}
        </when>
        <when test="userName != null and userName != ''">
            AND user_name = #{userName}
        </when>
        <otherwise>
            AND 1 = 2
        </otherwise>
    </choose>
</select>

Precautions:

In the above code, if not otherwise this restriction, when both id and userName is null, all users will be check out, but we interfaces return value is SysUser, when the results will be given more time. After adding otherwise conditions, due to where conditions are not satisfied, so in this case you can not find results.

Finally, add the following test method SysUserMapperTest test class:

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

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

        // 按id查询
        SysUser query = new SysUser();
        query.setId(1L);
        query.setUserName("admin");
        SysUser sysUser = sysUserMapper.selectByIdOrUserName(query);
        Assert.assertNotNull(sysUser);

        // 只按userName查询
        query.setId(null);
        sysUser = sysUserMapper.selectByIdOrUserName(query);
        Assert.assertNotNull(sysUser);

        // id 和 userName 都为空
        query.setUserName(null);
        sysUser = sysUserMapper.selectByIdOrUserName(query);
        Assert.assertNull(sysUser);
    } 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 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

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

DEBUG [main] - ==> Parameters: admin(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 1 = 2

DEBUG [main] - ==> Parameters:

DEBUG [main] - <== Total: 0

2. where usage

Where the role of the label: if the tag element included in the return value, where a is inserted, if the string is the beginning of the AND and OR where later, they will be removed.

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:

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

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

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

When if conditions are not met, where there is no element content, Sql statement at this time there will be no where, grammatically correct.

If the condition is met if the content is in a condition where the elements beginning with AND, where will automatically remove beginning and, to ensure the correct Sql statement.

Finally, add the following test method SysUserMapperTest test class:

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

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

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

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

        // 同时按用户民和邮箱查询
        query = new SysUser();
        query.setUserName("ad");
        query.setUserEmail("[email protected]");
        sysUserList = sysUserMapper.selectByUserWhere(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 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 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 user_name LIKE CONCAT(’%’,?,’%’) AND user_email = ?

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

DEBUG [main] - <== Total: 0

3. set usage

Action tag set: If an element included in the tag returns a value, a set is inserted, the latter if the string is set, the end, this will eliminate the comma.

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:

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

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

<update id="updateByIdSelectiveSet">
    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},
    </set>
    WHERE id = #{id}
</update>

** Note: ** In order to avoid all the conditions are not met, the generated Sql statement does not set the label, so the last with the id = #{id},assignment of such necessity exists.

Finally, add the following test method SysUserMapperTest test class:

@Test
public void testUpdateByIdSelectiveSet() {
    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.updateByIdSelectiveSet(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

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/103287319