ibatis中传List参数

一.ibatis中用list传参数的方式

<select id="getcount" parameterClass="java.util.ArrayList" resultClass="int">  
        select count(id) from `user` where id in  
        <iterate  open="(" close=")" conjunction="," >  
           #[]#  
        </iterate>  
         and status=1  
</select>

  程序调用的方式

public Integer getcount(List<Integer> friendsIds) throws SQLException {  
    Integer count(Integer)client.queryForObject("User.getcount", friendsIds);  
    return count;  
}

  还可以在程序把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

<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;    
}

 

文章来源:http://www.cnblogs.com/lcngu/p/5083695.html

posted on 2018-02-22 16:17  bijian1013  阅读(722)  评论(0)    收藏  举报

导航