溫馨提示×

Mybatis中case when如何處理復(fù)雜邏輯

小樊
81
2024-10-13 15:06:34
欄目: 編程語言

在 MyBatis 中,可以使用 <if> 標(biāo)簽結(jié)合 SQL 語句中的 CASE WHEN 來處理復(fù)雜的邏輯。以下是一個示例:

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

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

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

<select id="findPersons" parameterType="map" resultMap="personResultMap">
    SELECT * FROM person
    <where>
        <if test="name != null">
            AND name = #{name}
        </if>
        <if test="age != null">
            AND age = #{age}
        </if>
        <if test="minAge != null and maxAge != null">
            AND age BETWEEN #{minAge} AND #{maxAge}
        </if>
    </where>
</select>

在這個示例中,我們使用 <where> 標(biāo)簽來確保查詢條件以 “AND” 連接。<if> 標(biāo)簽用于根據(jù)參數(shù)是否為 null 來決定是否添加相應(yīng)的查詢條件。

接下來,創(chuàng)建一個結(jié)果映射文件 personResultMap

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

現(xiàn)在,你可以在 Java 代碼中調(diào)用這個查詢方法:

List<Person> persons = sqlSession.selectList("com.example.PersonMapper.findPersons", null);

這個示例展示了如何在 MyBatis 中使用 <if> 標(biāo)簽和 SQL 語句中的 CASE WHEN 來處理復(fù)雜的邏輯。你可以根據(jù)需要調(diào)整查詢條件和邏輯。

0