注:Mybatis实现批量更新有三种方式,分别是使用foreach标签、使用SQL的case when语句和使用动态SQL的choose语句。具体实现方法如下:
1:使用foreach标签
<update id="pubAndTakes">
<foreach collection="idList" item="item" separator=";" open="begin" close=";end;">
UPDATE LY_SJS_WDZM_YXLXD_PZRY SET ZT = '1' , CJSJ = TO_CHAR(SYSDATE,'yyyy-MM-dd hh:mm:ss')
,BBH = #{item.bbh}
WHERE ZT = #{item.zt} AND ID = #{item.id}
</foreach>
</update>
2:使用SQL的case when语句
<update id="updateBatch" parameterType="java.util.List">
UPDATE your_table
SET your_column1 =
<foreach collection="list" item="item" separator=",">
WHEN your_id = #{item.id} THEN #{item.column1}
</foreach>
WHERE your_id IN
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item.id}
</foreach>
</update>
3:使用 Case
语句
在 SQL 更新语句中使用 CASE
语句,根据条件进行更新。这种方式可以避免使用 foreach
或 BatchExecutor
,但对于大量数据可能性能较差。
<update id="updateBatch" parameterType="java.util.List">
UPDATE your_table
SET your_column1 =
CASE
<foreach collection="list" item="item" separator=" ">
WHEN your_id = #{item.id} THEN #{item.column1}
</foreach>
END,
your_column2 =
CASE
<foreach collection="list" item="item" separator=" ">
WHEN your_id = #{item.id} THEN #{item.column2}
</foreach>
END
WHERE your_id IN
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item.id}
</foreach>
</update>
这种方式的 SQL 语句会根据条件进行更新,适用于一次性批量更新较少的记录。
注:
使用BatchExecutor
批处理器
MyBatis 提供了 BatchExecutor
批处理器,可以在一次数据库会话中批量执行多个 SQL 语句。这种方式需要在代码中手动创建批处理器,并调用 batch
方法执行批量更新。注意,此方式可能不支持所有数据库,因此请仔细查阅文档以确认你的数据库是否支持。
SqlSession sqlSession = sqlSessionFactory
.openSession(ExecutorType.BATCH, false);
YourMapper mapper = sqlSession.getMapper(YourMapper.class);
try {
for (YourEntity entity : entities) {
mapper.update(entity);
}
sqlSession.commit();
} finally {
sqlSession.close();
}