在 MyBatis 中,<select> 標簽用于定義 SQL 查詢語句,而 where 條件則是用于過濾查詢結果的。通常情況下,我們不需要在 <select> 標簽中直接編寫 where 條件,因為 MyBatis 會自動處理查詢參數。但是,在某些情況下,我們可能需要手動指定 where 條件,這時可以通過以下兩種方式實現:
<if> 標簽判斷條件是否為空,如果不為空,則添加 where 子句。<select id="findUserById" parameterType="int" resultType="User">
SELECT * FROM user
<where>
<if test="id != null">
AND id = #{id}
</if>
</where>
</select>
在這個例子中,如果 id 參數不為空,MyBatis 會自動生成一個帶有 WHERE 子句的 SQL 查詢語句。
<choose>、<when> 和 <otherwise> 來實現更復雜的條件判斷。<select id="findUserByIdAndName" parameterType="map" resultType="User">
SELECT * FROM user
<where>
<choose>
<when test="id != null">
AND id = #{id}
</when>
<when test="name != null and name != ''">
AND name = #{name}
</when>
<otherwise>
<!-- 這里可以添加默認的查詢條件,例如: -->
AND age = 18
</otherwise>
</choose>
</where>
</select>
在這個例子中,我們根據 id 和 name 參數的值來動態生成 where 子句。如果 id 不為空,則添加 id = #{id} 條件;如果 name 不為空且不為空字符串,則添加 name = #{name} 條件;否則,添加一個默認的查詢條件 age = 18。
總之,MyBatis 的 <select> 標簽與 where 條件的搭配使用可以通過 <if> 標簽或動態 SQL 標簽來實現。在實際開發中,根據需求選擇合適的方式來實現條件過濾。