Ibatis中用list傳參數的方式。
Java代碼 select count(id) from `user` where id in #[]# and status=1 。
1 <select id="getcount" parameterClass="java.util.ArrayList" resultClass="int"> 2 select count(id) from `user` where id in 3 <iterate open="(" close=")" conjunction="," > 4 #[]# 5 </iterate> 6 and status=1 7 </select>
程序調用的方式
java代碼
1 public Integer getcount(List<Integer> friendsIds) throws SQLException { 2 Integer count(Integer)client.queryForObject("User.getcount", friendsIds); 3 return count; 4 }
還可以在程序把list拼成String,用string當參數傳給Ibatis查詢,但是要注意在Ibatis的xml中要用 $parameter$來取參數,以保證Ibatis不改變參數的性質,如果用#parameter#取參數,此種傳參的辦法就不行了 。
select count(id) from `user` where id in ($parameter$)(注意:容易導致sql注入)
用迭代來實現,用parameterClass 來接收然后通過<iterate>遍歷整個集合
Iterate的屬性:
prepend - 可被覆蓋的SQL語句組成部分,添加在語句的前面(可選)
property - 類型為java.util.List的用於遍歷的元素(必選)
open - 整個遍歷內容體開始的字符串,用於定義括號(可選)
close -整個遍歷內容體結束的字符串,用於定義括號(可選)
conjunction - 每次遍歷內容之間的字符串,用於定義AND或OR(可選)
<iterate> 遍歷類型為java.util.List的元素。
例子:
user.xml
1 <select id="getUser" parameterClass="java.util.Map" resultClass="userModel"> 2 3 <![CDATA[ select * from userinfo WHERE (userid in 4 5 ]]> 6 7 <iterate property="personList" open="(" close=")" conjunction=","> 8 9 #personList[].userId# 10 11 <!--$personList[].userId$--> 12 13 </iterate> 14 15 <![CDATA[ 16 17 ) 18 19 ]]> 20 21 </select>
注意:使用<iterate>時,在List元素名后面包括方括號[]非常重要,方括號[]將對象標記為List,以防解析器簡單地將 List輸出成String。
(#) 使用的是PreparedStatement 機制,生成的SQL字符串中含有很多?,這些會被動態的添加參數進去查詢
($) 中的變量好比字符串直接替換。
Dao.java
1 public UserModel getUser(UserModel userModel) throws SQLException { 2 3 Map<String, Object> map = new HashMap<String, Object>(); 4 5 List<UserModel> list = new ArrayList<UserModel>(); 6 7 UserModel userModel1 = new UserModel(); 8 9 userModel1.setUserId("1"); 10 11 list.add(userModel1); 12 13 UserModel userModel2 = new UserModel(); 14 15 userModel2.setUserId("lsw"); 16 17 list.add(userModel2); 18 19 map.put("personList", list); 20 21 List sqlUserModelList = getSqlMapClientTemplate().queryForList("getUser", map); 22 23 UserModel sqlUserModel = new UserModel(); 24 25 return sqlUserModel; }