在MyBatis中,可以使用<choose>
、<when>
和<otherwise>
來(lái)實(shí)現(xiàn)多條件判斷語(yǔ)句。以下是一個(gè)示例:
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<choose>
<when test="name != null">
AND name = #{name}
</when>
<when test="age != null">
AND age = #{age}
</when>
<otherwise>
AND 1=1
</otherwise>
</choose>
</where>
</select>
在以上示例中,<choose>
用來(lái)包裹多個(gè)條件判斷,<when>
用來(lái)定義條件成立時(shí)的sql語(yǔ)句,<otherwise>
用來(lái)定義當(dāng)所有條件都不成立時(shí)的sql語(yǔ)句。在<when>
和<otherwise>
中使用test
屬性來(lái)指定條件判斷的表達(dá)式。
通過這種方式,可以簡(jiǎn)潔地實(shí)現(xiàn)多條件判斷,并且保持sql語(yǔ)句的可讀性和可維護(hù)性。