具体可参考:https://www.cnblogs.com/eternityz/p/12284760.html
<update id="batchUpdateByPrimaryKey"
parameterType="java.util.List">
update device_manage_info
<trim prefix="set" suffixOverrides=",">
<trim prefix="dmi_app_version = case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.dmiAppVersion!= null and item.dmiAppVersion!='' ">
when dmi_id = #{item.dmiId,jdbcType=BIGINT}
then #{item.dmiAppVersion,jdbcType=VARCHAR}
</if>
</foreach>
</trim>
<trim prefix="dmi_app_sys =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.dmiAppSys!= null and item.dmiAppSys!='' ">
when dmi_id = #{item.dmiId,jdbcType=BIGINT}
then #{item.dmiAppSys,jdbcType=VARCHAR}
</if>
</foreach>
</trim>
<trim prefix="dmi_member_status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.dmiMemberStatus!= null">
when dmi_id = #{item.dmiId,jdbcType=BIGINT}
then #{item.dmiMemberStatus,jdbcType=INTEGER}
</if>
</foreach>
</trim>
</trim>
where dmi_id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.dmiId,jdbcType=BIGINT}
</foreach>
<!-- where-->
<!-- <foreach collection="list" separator="or" item="item" index="index">-->
<!-- dmi_id=#{item.dmiId}-->
<!-- </foreach>-->
</update>
一、<trim prefix="dmi_app_version = case" suffix="end,">
prefix:放入的是需要更新的字段
二、collection="list"
list需要与dao接口参数名一致
三、
<if test="item.dmiAppVersion!= null and item.dmiAppVersion!='' ">
when dmi_id = #{item.dmiId,jdbcType=BIGINT}
then #{item.dmiAppVersion,jdbcType=VARCHAR}
</if>
when后面dmi_id这个是数据库字段,#{item.dmiId,jdbcType=BIGINT}必须是item.字段这种形式
then后面是需要更新的字段。
这句话的意思是,更新id在集合中的数据的dmiAppVersion字段。
注意:整型不需要:and item.dmiAppVersion!=''
四、如果有过个需要更新的条件可以使用多个
<trim prefix="dmi_member_status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.dmiMemberStatus!= null">
when dmi_id = #{item.dmiId,jdbcType=BIGINT}
then #{item.dmiMemberStatus,jdbcType=INTEGER}
</if>
</foreach>
</trim>
五、需要注意最后的循环
where dmi_id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.dmiId,jdbcType=BIGINT}
</foreach>
<!-- where-->
<!-- <foreach collection="list" separator="or" item="item" index="index">-->
<!-- dmi_id=#{item.dmiId}-->
<!-- </foreach>-->
不能够dmi_id= #{item.dmiId,jdbcType=BIGINT},否则不会更新数据,也不会报错(踩坑)
这里面有两种形式循环,但是结果都一样
结果如下:
UPDATE device_manage_info
SET dmi_app_version =
CASE
WHEN dmi_id = ? THEN
?
WHEN dmi_id = ? THEN
?
END,
dmi_app_sys =
CASE
WHEN dmi_id = ? THEN
?
WHEN dmi_id = ? THEN
?
END,
dmi_member_status =
CASE
WHEN dmi_id = ? THEN
?
WHEN dmi_id = ? THEN
?
END
WHERE
dmi_id =?
OR dmi_id =?