Mybatis動態SQL foreach標簽用法實例
需求:傳入多個 id 查詢用戶信息,用下邊兩個 sql 實現:
SELECT * FROM USERS WHERE username LIKE ’%張%’ AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE ’%張%’ AND id IN (10,89,16)
這樣我們在進行范圍查詢時,就要將一個集合中的值,作為參數動態添加進來。
這樣我們將如何進行參數的傳遞?
1、實體類
public class QueryVo implements Serializable { private List<Integer> ids; public List<Integer> getIds() {return ids; } public void setIds(List<Integer> ids) {this.ids = ids; } }
2、持久層接口
/*** 根據 id 集合查詢用戶* @param vo* @return*/List<User> findInIds(QueryVo vo);
3、映射文件
<!-- 查詢所有用戶在 id 的集合之中 --><select resultType='user' parameterType='queryvo'> <!-- select * from user where id in (1,2,3,4,5); -->select * from user <where> <if test='ids != null and ids.size() > 0'> <foreach collection='ids' open='id in ( ' close=')' item='uid' separator=','>#{uid} </foreach></if> </where></select>
SQL 語句:
select 字段 from user where id in (?)
foreach標簽用于遍歷集合,它的屬性
collection:代表要遍歷的集合元素,注意編寫時不要寫#{} open:代表語句的開始部分 close:代表結束部分 item:代表遍歷集合的每個元素,生成的變量名 sperator:代表分隔符以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: