在SQL語法中如果我們想使用in的話直接可以像如下一樣使用:
update user set status='1' where id in (1,2,3) ; select * from user where id in (1,2,3) ;
但是如果在MyBatis中的使用 in 操作符,像下面這樣寫的話,肯定會報錯:
@Update("update user set status=#{status} where id in #{userIds}")
public void updateUserStatus(@Param("userIds") String userIds, @Param("status") int status);
其中 userIds = (1,2,3)
這樣直接拼接的寫法,看似很簡單,在 findByCondition 用沒問題,但在動態SQL注解中MyBatis是不支持的。
上帝關上了一扇門,就肯定會打開一扇窗。
對於上面這種情況,MyBatis中提供了foreach語句來實現IN查詢。
foreach語法如下: foreach語句中, collection屬性的參數類型可以支持:List、數組、map集合
collection: 必須跟mapper.java中@Param標簽指定的元素名一樣
item: 表示在迭代過程中每一個元素的別名,可以隨便起名,但是必須跟元素中的#{}里面的名稱一樣。
index:表示在迭代過程中每次迭代到的位置(下標)
open:前綴, sql語句中集合都必須用小括號()括起來
close:后綴
separator:分隔符,表示迭代時每個元素之間以什么分隔
示例:
@Update({"<script>", "update user set status=#{status} where id in ", "<foreach collection=\"userIdList\" item=\"userId\" index=\"index\" open=\"(\" separator=\",\" close=\")\">", "#{userId}", "</foreach>", "</script>"}) public void updateUserStatus(@Param("userIdList") List<String> userIdList, @Param("status") int status);
共同學習,共同進步,若有補充,歡迎指出,謝謝!