您的位置:首页 > 其它

mybatis <forEach>标签的使用

2017-09-04 10:53 337 查看


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。


entity实体类

public class QueryVo(){
private User user;
private UserCustom userCustom;
private List<integer> ids;
}
1
2
3
4
5
1
2
3
4
5


Mapper

<select id="find" parameterType="qo" resultMap="userResult">
select * from `user`
<where>
<foreach collection="ids" open=" and id in(" close=")"
item="id" separator=",">
#{id}
</foreach>
</where>
limit 0,10
</select>
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10


测试代码

@Test
public void testFindByForeach(){
UserDaoImpl dao = new UserDaoImpl();
QueryObject queryObject = new QueryObject();
List<String> ids = new ArrayList<>();
ids.add("93365508879156507BA5FA7AD34ED9A10DC876DCC6BE7E08548587");
ids.add("93365566961612F12AF562B60641B8964B99202A80720834031994");
ids.add("9336561173424758F5F3B93D804D55AF41DE49B86EDE8D31235175");
ids.add("2222");
ids.add("111");
queryObject.setIds(ids);
List<User> userList = dao.find(queryObject);
System.out.println(userList);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
直接传递单个List 
传递List类型在编写mapper.xml没有区别,唯一不同的是只有一个List参数时它的参数名为list。


Mapper

<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>
1
2
3
4
5
6
7
8
9
10
11


1
2
3
4
5
6
7
8
9
10
11


传递单个数组(数组中是pojo):

<!-- 传递数组综合查询用户信息 -->
<select id="findByArray" parameterType="Object[]" resultType="user">
select * from user
<where>
<!-- 传递数组 -->
<if test="array!=null">
<foreach collection="array" index="index" item="item" open="and id in("separator=","close=")">
#{item.id}
</foreach>
</if>
</where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: