向sql传递数组或List,mybatis使用foreach解析;foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合;foreach元素的属性主要有item,index,collection,open,separator,close

1. foreach参数解析

  • 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种情况:
    • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
    • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    • 如果使用Map封装了,collection的属性值为对应的Key

2. array数组的类型

UserMapper.java

    List<User> getUserByIds02(Integer[] ids);

UserMapper.xml

    <select id="getUserByIds02" resultType="com.example.practice.domain.User">
        SELECT * FROM `user` u WHERE u.`id` IN
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">#{item}</foreach>
    </select>

3. list的类型

UserMapper.java

    List<User> getUserByIds03(List<Integer> listIds);

UserMapper.xml

    <select id="getUserByIds03" resultType="com.example.practice.domain.User">
        SELECT * FROM `user` u WHERE u.`id` IN
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">#{item}</foreach>
    </select>

4. 参考文献

Mybatis之foreach用法 List和Array,对象
mybatis 中 foreach collection的用法小结(三种)

更多推荐

mybatis使用foreach遍历list集合或者array数组方式