MyBatis提供了多種方式來更新大量數據。
<update id="updateBatch" parameterType="java.util.List">
UPDATE table_name
SET column1 = #{list[0].column1},
column2 = #{list[0].column2}
WHERE id = #{list[0].id}
<foreach collection="list" item="item" index="index" separator="UNION ALL">
SELECT #{item.column1}, #{item.column2}, #{item.id}
</foreach>
</update>
<update id="updateBatch" parameterType="java.util.Map">
UPDATE table_name
<set>
<if test="column1 != null">column1 = #{column1},</if>
<if test="column2 != null">column2 = #{column2},</if>
</set>
WHERE id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
YourMapper mapper = sqlSession.getMapper(YourMapper.class);
for (YourEntity entity : entities) {
mapper.update(entity);
}
sqlSession.commit();
}
以上是一些常用的更新大量數據的方式,在實際使用時可以根據具體情況選擇合適的方法。