Ibatis中传List参数

Ibatis中用list传参数的方式 

Java代码  select count(id) from `user` where id in #[]# and status=1 " quality="high" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">  收藏代码
  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$) 
 
ibatis 数组参数
 

用迭代来实现,用parameterClass 来接收然后通过<iterate>遍历整个集合

Iterate的属性:
prepend - 可被覆盖的SQL语句组成部分,添加在语句的前面(可选)
property - 类型为java.util.List的用于遍历的元素(必选)
open - 整个遍历内容体开始的字符串,用于定义括号(可选)
close -整个遍历内容体结束的字符串,用于定义括号(可选)
conjunction - 每次遍历内容之间的字符串,用于定义AND或OR(可选)
<iterate> 遍 历类型为java.util.List的元素。

例子: 

User.xml

<select id="getUser" parameterClass="java.util.Map" resultClass="userModel">

<![CDATA[ select * from userinfo WHERE (userid in

]]>

  <iterate property="personList" open="(" close=")" conjunction=",">

    #personList[].userId#

<!--$personList[].userId$-->

           </iterate>

<![CDATA[

)

]]>

</select>

注意:使用<iterate>时,在List元素名后面包括方括号[]非常重要,方括号[]将对象标记为List,以防解析器简单地将 List输出成String。

(#) 使用的是PreparedStatement 机制,生成的SQL字符串中含有很多?,这些?会被动态的添加参数进去查询

($) 中的变量好比字符串直接替换。

Dao.java

public UserModel getUser(UserModel userModel) throws SQLException {                      

Map<String, Object> map = new HashMap<String, Object>();

List<UserModel> list = new ArrayList<UserModel>();

UserModel userModel1 = new UserModel();

userModel1.setUserId("1");

list.add(userModel1);

UserModel userModel2 = new UserModel();

userModel2.setUserId("lsw");                                 

list.add(userModel2);    

map.put("personList", list);

List sqlUserModelList = getSqlMapClientTemplate().queryForList("getUser", map);

UserModel sqlUserModel = new UserModel();                     

return sqlUserModel;    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值