一、实体类
@Data
@TableName("mdm_alarm_sub")
public class MdmAlarmSubEntity extends BaseEntity {
@TableId(type = IdType.AUTO)
private Integer id;
private Integer alarmSetId;
private String isOn;
private String isPhone;
private String isEmail;
private String phone;
private String email;
private String rdStatus;
}
二、Mapper
Boolean updateBatch(@Param("list") List<MdmAlarmSubEntity> list);
三、Mybatis
<update id="updateBatch" parameterType="java.util.List">
update mdm_alarm_sub
<trim prefix="set" suffixOverrides=",">
<trim prefix="alarm_set_id=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.alarmSetId!=null">
when id=#{item.id} then #{item.alarmSetId}
</if>
<if test="item.alarmSetId!=null">
when id=#{item.id} then mdm_alarm_sub.alarm_set_id
</if>
</foreach>
</trim>
<trim prefix="is_on=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.isOn!=null">
when id=#{item.id} then #{item.isOn}
</if>
<if test="item.isOn!=null">
when id=#{item.id} then mdm_alarm_sub.is_on
</if>
</foreach>
</trim>
<trim prefix="is_phone=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.isPhone!=null">
when id=#{item.id} then #{item.isPhone}
</if>
<if test="item.isPhone!=null">
when id=#{item.id} then mdm_alarm_sub.is_phone
</if>
</foreach>
</trim>
<trim prefix="is_email=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.isEmail!=null">
when id=#{item.id} then #{item.isEmail}
</if>
<if test="item.isEmail!=null">
when id=#{item.id} then mdm_alarm_sub.is_email
</if>
</foreach>
</trim>
<trim prefix="phone=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.phone!=null">
when id=#{item.id} then #{item.phone}
</if>
<if test="item.phone!=null">
when id=#{item.id} then mdm_alarm_sub.phone
</if>
</foreach>
</trim>
<trim prefix="email=case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.email!=null">
when id=#{item.id} then #{item.email}
</if>
<if test="item.email!=null">
when id=#{item.id} then mdm_alarm_sub.email
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" separator="," open="(" close=")" item="item" index="index">
#{item.id}
</foreach>
</update>
四、说明
1、foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
2、foreach元素的属性主要有 item,index,collection,open,separator,close。
(1)item表示集合中每一个元素进行迭代时的别名
index指定一个名字,用于表示在迭代过程中,每次迭代到的位置
(2)open表示该语句以什么开始
(3)separator表示在每次进行迭代之间以什么符号作为分隔 符
(4)close表示以什么结束
在使用
3、foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下三种情况:
(1)如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
(2)如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
(3)如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
注意:
1、这里得prefix属性中的内容要和数据库字段一致,下面的if里面的内容才是对应实体类里的值,这点务必谨记,楼主就是在这里踩了巨坑!!!;
2、Mapper接口这里要加@Parm注解,内容对应着foreach标签中collection属性的值