mybatis中foreach说明
- 你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时候,MyBatis 会自动将它包装在一个 Map 中,用名称作为键。List 实例将会以“list”作为键,而数组实例将会以“array”作为键。
- foreach元素的属性主要有 item,index,collection,open,separator,close。
- item表示集合中每一个元素进行迭代时的别名,
- index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
- open表示该语句以什么开始,
- separator表示在每次进行迭代之间以什么符号作为分隔符,
- close表示以什么结束。
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map或者Object。
1、传递单个list
public List<User> selectByList(List<User> list);
<select id="selectByList" parameterType="java.util.List" resultType="user">
select * from user
<where>
<!-- 传递List,List中是pojo -->
<if test="list!=null">
<foreach collection="list" item="item" open="and id in("separator=","close=")">
#{item.id}
</foreach>
</if>
</where>
</select>
传递单个数组
public int deleteByIds(String[] ids);
<delete id="deleteByIds" parameterType="java.lang.String">
DELETE FROM cms_article
WHERE article_id in
<foreach item="item" index="index" collection="array" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
如果是多个参数时,就需要通过对象或者map进行传递
1、封装成对象
/**组id数组 */
private Long[] userGroupIds;
public Long[] getUserGroupIds() {
return userGroupIds;
}
public void setUserGroupIds(Long[] userGroupIds) {
this.userGroupIds = userGroupIds;
}
通过“.”的形式获取
List<ExaminationRoomDto> getExaminationRoomList(@Param("dto")ExaminationRoomDto dto);
<if test="dto.userGroupIds !=null and dto.userGroupIds.length > 0">
and e.user_group_id in
<foreach collection="dto.userGroupIds" item="userGroupIds" index="index" open="(" close=")" separator=",">
#{userGroupIds}
</foreach>
</if>
2、写成Map
Map<String, Object> map = new HashMap<String, Object>();
List<String> userlist = new ArrayList<String>();
userlist.add("admin");
map.put("userids", userlist);
List<UserInfo> selectUserInfoByForEach(Map<String,Object> map);
<select id="selectUserInfoByForEach" parameterType="Map"
resultMap="UserInfoResult">
select * from userinfo
<if test="userids!=null">
where userid in
<foreach item="ParamsId" collection="userids" index="index"
open="(" separator="," close=")">
#{ParamsId}
</foreach>
</if>
</select>