How can MyBatis update data in bulk?
MyBatis offers two options for implementing batch data updates:
- Using the foreach tag: You can use the foreach tag to make batch modifications to each element in a collection. Example code is shown below:
<update id="batchUpdate" parameterType="java.util.List">
UPDATE table_name
SET column1 = #{listProperty.property1},
column2 = #{listProperty.property2}
WHERE id = #{listProperty.id}
</update>
In Java code, calling the batchUpdate method with a List containing multiple objects is all that is needed.
- Using dynamic SQL: Batch updates can be achieved through dynamic SQL statements. Example code is shown below:
<update id="batchUpdate" parameterType="java.util.Map">
<foreach collection="list" item="item" index="index" open="(" close=")" separator=";">
UPDATE table_name
SET column1 = #{item.property1},
column2 = #{item.property2}
WHERE id = #{item.id}
</foreach>
</update>
In Java code, when invoking the batchUpdate method mentioned above, pass in a Map object containing a List property named “list” which holds the objects that need to be updated in bulk.
Both methods can achieve bulk data modification, the selection between the two depends on the specific requirements and actual circumstances.