delete from  xxx_table where id  in 
<foreach collection="list" item="item" index="index" open="(" separator="," close=")"> 
		#{item}
</foreach>  => (1,2,3,4)

foreach标签:主要应用于批量删除与批量插入操作。

foreach标签包含的的常用属性有collection,item,index,open,separator,close

  • collection:表示迭代集合的名称,自定义名称,可以使用@Param注解指定
    • 只有一个List/Array/Map类型参数时,如果不加@Param注解,collection分别必须填:list、array、map中的key属性
    • 有多个参数时,不加@Param注解,collection和默认参数名称一致
    • 如果加@Param注解,都和注解定义一致
  • item:表示本次迭代获取的元素,自定义名称;表示本次迭代获取的元素,若collection为List、Set或者数组,则表示其中的元素;若collection为map,则代表key-value的value,该参数为必选
  • separator:分隔符,mybatis会在每次迭代后给sql语句append上separator属性指定的字符,该参数为可选项
  • open:表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项
  • close:表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项
  • index:在list、Set和数组中,index表示当前迭代的位置,在map中,index代指是元素的key,该参数是可选项。

在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况

1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key。

使用示例

对于前两种情况的使用非常简单易懂,这里我们对第三种情况进行简单的使用,来进行一个批量插入。

controller层

        LocalDateTime localDateTime = LocalDateTime.now();
        teacherCourseList.setCreate_time(localDateTime);
        teacherCourseList.setUpdate_time(localDateTime);
        log.info("入参======="+teacherCourseList);

        Map<String,Object> map=new HashMap<>();
        map.put("username",teacherCourseList.getUsername());
        map.put("CourseList",teacherCourseList.getCourseList());
        map.put("create_time",teacherCourseList.getCreate_time());
        map.put("update_time",teacherCourseList.getUpdate_time());
        courseService.batchInsert(map);

xml

<insert id="batchInsert">
    insert into ref_teacher_course (teacher_id,course_id,create_time,update_time)
    values 
    <foreach collection="teacherCourseList.CourseList" item="item" index="index" separator=",">
        (#{teacherCourseList.username},
        #{item},
        #{teacherCourseList.create_time},
        #{teacherCourseList.update_time})
    </foreach>
</insert>

mapper

 void batchInsert(@Param("teacherCourseList") Map map);

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐