1、我们使用Mybatis批量更新时,通常是这样的:
Mapper:
void batchUpdateDemo(@Param("list") List<DemoDO> list);
XML:
<update id="batchUpdateDemo"> update `demo_table` set a = <foreach collection="list" item="udo" separator=" " open="case id" close="end ,"> when #{udo.id} then #{udo.a} </foreach> b = <foreach collection="list" item="udo" separator=" " open="case id" close="end"> when #{udo.id} then #{udo.b} </foreach> where id in <foreach collection="list" item="udo" separator="," open="(" close=")"> #{udo.id} </foreach> </update>
字段少的时候可以接受 ,但是一多就emmm...
2、那么mybatisPlus可以解决这一痛点
mybatis-plus提供了
IService 及其实现类 ServiceImpl<M extends BaseMapper<T>, T>
IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 )
我们在使用时只需继承该实现类即可,前提需要定义继承BaseMapper的Mapper和相应DO
public class DemoServiceImpl extends ServiceImpl<DemoMapper,DmeoDO> {...}
使用:
@Autowired DemoServiceImpl cpService; public void mybatisPlusTest() { List<DemoDO> list = new ArrayList<>(); DemoDO cdo1 = new DemoDO(); cdo1.setId(4); cdo1.setName("测试11"); DemoDO cdo2 = new DemoDO(); cdo2.setId(5); cdo2.setName("测试22"); list.add(cdo1); list.add(cdo2); cpService.updateBatchById(list,1000); }
mybatis-plus安装可以参考:https://mp.csdn.net/postedit/102587131
3、感兴趣的同学可以看一下batchUpdate的源码,底层还是使用了mybatis:
public boolean updateBatchById(Collection<T> entityList, int batchSize) { Assert.notEmpty(entityList, "error: entityList must not be empty"); String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID); try (SqlSession batchSqlSession = sqlSessionBatch()) { int i = 0; for (T anEntityList : entityList) { MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>(); param.put(Constants.ENTITY, anEntityList); batchSqlSession.update(sqlStatement, param); if (i >= 1 && i % batchSize == 0) { batchSqlSession.flushStatements(); } i++; } batchSqlSession.flushStatements(); } return true; }