Batch update multiple fields in the mybatis
It recommended the following:
Embodiment 1: In Dao layer interface:
void updateBatch(@Param("list")List<Student> list);
In the corresponding mapper file as follows:
<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>
The above sql statement printed out, it should look like this:
update student
set age = case
ID When = {# # {item.status the then item.id}} // here should be <foreach> Expand value When item.id ID = {# #} {the then item.status} ....
end,
name = case
when id = #{item.id} then #{item.status}
...
end
where id in (?,?,?,?...);
<Trim> Attribute Description
1.prefix, suffix represents added before or after the content portion of the tag trim package
2. If prefixOverrides Meanwhile, suffixOverrides would represent a prefix, suffix Overrides the overlay content.
3. If only prefixOverrides, suffixOverrides represents the beginning or end of the deletion of the specified content xxxOverides
Embodiment 2: as above layer interface methods defined in Dao
mapper file as follows:
<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>