码迷,mamicode.com
首页 > 其他好文 > 详细

Ibatis中传List参数

时间:2015-12-28 21:46:47      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

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注入)

ibatis 数组参数
 

用迭代来实现,用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;    }

 

Ibatis中传List参数

标签:

原文地址:http://www.cnblogs.com/lcngu/p/5083695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!