mybatis處理集合、循環、數組和in查詢等語句的使用
阿新 • • 發佈:2017-06-30
round style 數組 cti abstract 進行 每一個 過濾 註入
在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>
mybatis處理集合、循環、數組和in查詢等語句的使用