在Mybatis的xml配置中使用集合,主要是用到了foreach動態語句。
foreach的參數:
foreach元素的屬性主要有 item,index,collection,open,separator,close。
item表示集合中每一個元素進行迭代時的別名.
index指定一個名字,用於表示在迭代過程中,每次迭代到的位置.
open表示該語句以什么開始
separator表示在每次進行迭代之間以什么符號作為分隔符.
close表示以什么結束.
1. Mybatis生成select * from table where id in(1,2,...,n)語句的查詢
我們一般的做法是在方法的參數處指定傳入的參數名稱,在xml中使用的時候,集合的名稱要和方法的Param的名稱一致,這樣便於閱讀和理解,
然后是在對應的xml文件中使用foreach循環。
java代碼如下:
public abstract List<Model> findByIds(@Param("ids")List<Integer> ids);
對應的xml代碼如下:
select * from table <where> id in <foreach collection="ids" item="item" index="index" open="(" separator="," close=")">#{item}</foreach> </where>
2.Mybatis保存多條記錄
我們同樣是通過foreach的方法來實現,這里我們巧妙的利用了sql的語法規則用Mybatis的foreach動態語句來處理。
java代碼:
public abstract void saves(@Param("tables")List<Model> tables);
xml代碼:
insert into table(name,addtime) values <foreach collection="tables" item="item" index="index" separator=","> (#{item.name},#{item.addtime}) </foreach>
以上方法Mybatis會幫我們進行sql注入攔截,Mybatis如果采用#{xxx}的形式設置參數,Mybatis會進行sql注入的過濾。如果采用的是${xxx},Mybatis不會進行sql注入過濾,而是直接將參入的內容輸出為sql語句。
判斷集合是否有值
<if test="list!=null and list.size()>0"></if>