一、需求 後臺使用orcale資料庫,mybatis做持久層,前臺搜索功能,根據類型搜索,但是資料庫中沒有類型欄位, 所以需要在where條件語句中進行判斷,當type == x1 時和type == x2時where中的判斷條件不同 二、解決 <select id = "" resultMap = ...
一、需求
後臺使用orcale資料庫,mybatis做持久層,前臺搜索功能,根據類型搜索,但是資料庫中沒有類型欄位,
所以需要在where條件語句中進行判斷,當type == x1 時和type == x2時where中的判斷條件不同
二、解決
<select id = "" resultMap = "">
select * from table
<where>
<if test="type == 'x1' ">
and 條件1;
</if>
<if test="type == 'x2' ">
and 條件2;
</if>
</where>
</select>
或者
<select id = "" resultMap = "">
select * from table
<choose>
<when test=" type == 'x1' '">
where 條件1;
</when >
<when test=" type == 'x2' '">
where 條件2;
</when >
<otherwise>
條件3; // 可以為空
</otherwise>
</choose>
<if test="type == 'x2' "> //如果除了以上條件外還有判斷的條件,放在chose標簽外,不用再寫where
and 條件2;
</if>
</select>
再或者
<select id = "" resultMap = "">
select * from table
<where>
<choose>
<when test=" type == 'x1' '">
條件1;
</when >
<when test=" type == 'x2' '">
條件2;
</when >
<otherwise>
條件3; // 可以為空
</otherwise>
</choose>
<if test="type == 'x2' "> //如果除了以上條件外還有判斷的條件,放在chose標簽外,不用再寫where
and 條件2;
</if>
</where>
</select>
choose標簽是按順序判斷其內部when標簽中的test條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when 的條件都不滿則時,則執行 otherwise 中的sql。