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();
}
以上是一些常用的更新大量数据的方式,在实际使用时可以根据具体情况选择合适的方法。