Mybatis中case when怎樣實(shí)現(xiàn)動(dòng)態(tài)查詢

小樊
81
2024-10-13 15:16:36

在 MyBatis 中,可以使用 <if> 標(biāo)簽結(jié)合 SQL 的 CASE WHEN 語(yǔ)句來(lái)實(shí)現(xiàn)動(dòng)態(tài)查詢。以下是一個(gè)簡(jiǎn)單的示例:

首先,創(chuàng)建一個(gè)實(shí)體類 User

public class User {
    private Integer id;
    private String name;
    private Integer age;
    // 省略 getter 和 setter 方法
}

然后,在 MyBatis 的映射文件中編寫(xiě)動(dòng)態(tài)查詢的 SQL:

<select id="findUsersByCondition" resultMap="UserResultMap">
    SELECT * FROM user
    <where>
        <if test="id != null">
            AND id = #{id}
        </if>
        <if test="name != null and name != ''">
            AND name LIKE CONCAT('%', #{name}, '%')
        </if>
        <if test="age != null">
            AND age = #{age}
        </if>
    </where>
    <if test="orderBy != null and orderBy != ''">
        ORDER BY ${orderBy}
    </if>
</select>

在這個(gè)示例中,我們使用了 <where> 標(biāo)簽來(lái)自動(dòng)處理 SQL 語(yǔ)句中的 WHERE 子句,避免了在查詢條件為空時(shí)出現(xiàn)多余的 AND 關(guān)鍵字。同時(shí),我們還使用了 <if> 標(biāo)簽來(lái)根據(jù)傳入的參數(shù)動(dòng)態(tài)生成查詢條件。

接下來(lái),創(chuàng)建一個(gè)結(jié)果映射類 UserResultMap

<resultMap id="UserResultMap" type="com.example.User">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="age" column="age"/>
</resultMap>

最后,在你的 DAO 接口中添加一個(gè)方法調(diào)用這個(gè)映射文件中的 SQL:

public interface UserDao {
    List<User> findUsersByCondition(@Param("id") Integer id, @Param("name") String name, @Param("age") Integer age, @Param("orderBy") String orderBy);
}

現(xiàn)在,你可以通過(guò)傳入不同的參數(shù)來(lái)調(diào)用 findUsersByCondition 方法,實(shí)現(xiàn)動(dòng)態(tài)查詢。例如:

List<User> users = userDao.findUsersByCondition(1, null, null, "age DESC");

0