MyBatis <forEach> 标签的使用

MyBatis 标签的使用

  • 你可以传递一个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;
}

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>

测试代码

@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);
}
  • 直接传递单个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>

传递单个数组(数组中的pojo)

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

猜你喜欢

转载自blog.csdn.net/liguangix/article/details/80840669