向sql传递数组或List,mybatis使用foreach解析
foreach元素的属性主要有item,index,collection,open,separator,close。
- item:集合中元素迭代时的别名,该参数为必选。
- index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
- open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
- separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
- close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
- collection:
foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3. 如果使用Map封装了,collection的属性值为对应的Key
1、array数组的类型
UserMapper.java
List<User> findUser_array(int [] ids)throws Exception;
UserMapper.xml
<!--单参数array数组的类型-->
<select id="findUser_array" resultType="com.xiaomin.page.pojo.User">
select * from sys_user
<where>
<foreach collection="array" item="item" open="and id in(" separator="," close=")">
#{item}
</foreach>
</where>
</select>
Controller.java
@RequestMapping("/findUser_array")
@ResponseBody
public List<User> foreach_test()throws Exception{
int [] ids=new int[]{1,2,3};
List<User> list = userMapper.findUser_array(ids);
return list;
}
示例:
2、list的类型
UserMapper.java
List<User> findUser_list(List<Integer>list)throws Exception;
UserMapper.xml
<!--list类型-->
<select id="findUser_list" resultType="com.xiaomin.page.pojo.User">
select * from sys_user
<where>
<foreach collection="list" item="user_id" open="and id in(" separator="," close=")">
#{user_id}
</foreach>
</where>
</select>
Controller.java
/**
* list类型
* @return
* @throws Exception
*/
@RequestMapping("/findUser_list")
@ResponseBody
public List<User> findUser_list()throws Exception{
List<User> list = userMapper.findUser_list(Arrays.asList(new Integer[]{1,2,3,6}));
return list;
}
测试截图:
3、对象类型
UserMapper.java
List<User> findUser_obj(UserQueryVo vo)throws Exception;
UserMapper.xml
<!--对象类型-->
<select id="findUser_obj" parameterType="com.xiaomin.page.pojo.vo.UserQueryVo" resultType="com.xiaomin.page.pojo.User">
select * from sys_user
<where>
<if test="ids !=null">
<foreach collection="ids" item="user_id" open="and id in (" separator="," close=")">
#{user_id}
</foreach>
</if>
</where>
</select>
Controller.java
/**
* 对象类型
* @return
* @throws Exception
*/
@RequestMapping("/findUser_obj")
@ResponseBody
public List<User> findUser_obj()throws Exception{
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
UserQueryVo queryVo = new UserQueryVo();
queryVo.setIds(ids);
List<User> list = userMapper.findUser_obj(null);
return list;
}
测试截图: