在mybatis中批量更新多個字段java
推薦使用以下操做:sql
方式1:在Dao層接口中:mybatis
void updateBatch(@Param("list")List<Student> list);
在對應的mapper文件中以下:app
<update id="updateBatch" parameType="java.lang.List">
update student
<trim prefix="set" suffixOverrides=",">
<trim prefix=" age = case " suffix="end,">
<foreach collection="list" item="stu" index="index">
<if test=" item.age != null and item.id != null">
when id = #{item.id} then #{item.age}
</if>
<if test=" item.age == null and item.id != null">
when id = #{item.id} then mydata_table.age //原始值
</if>
</foreach>
</trim>
<trim prefix=" name = case" suffix="end,">
<foreach collection="list" item="stu" index="index">
<if test=" item.name!= null and item.id != null">
when id = #{item.id} then #{item.name}
</if>
<if test=" item.name == null and item.id != null">
when id = #{item.id} then mydata_table.name //原始值
</if>
</foreach>
</trim>
</trim>
</update>
上面的sql語句打印出來,應該是這個樣子的:ide
update student
set age = case
when id = #{item.id} then #{item.status}//此處應該是<foreach>展開值
when id = #{item.id} then #{item.status}
....
end,
name = case
when id = #{item.id} then #{item.status}
...
end
where id in (?,?,?,?...);
<trim>屬性說明 spa
1.prefix,suffix 表示在trim標籤包裹的部分的前面或者後面添加內容
2.若是同時有prefixOverrides,suffixOverrides 表示會用prefix,suffix覆蓋Overrides中的內容。
3.若是隻有prefixOverrides,suffixOverrides 表示刪除開頭的或結尾的xxxOverides指定的內容 code
方式2:在Dao層接口方法定義同上blog
mapper文件以下:接口
<update id="updateBatch" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> update student <set> name=#{item.name}, age = #{item.age} </set> where id = #{item.id} </foreach> </update>