MybatisPlus批量更新

1、我们使用Mybatis批量更新时,通常是这样的:

Mapper:

void batchUpdateDemo(@Param("list") List list);

XML:


    update `demo_table`
    set a =
    
        when #{udo.id} then #{udo.a}
    
    b =
    
        when #{udo.id} then #{udo.b}
    
    where id in
    
        #{udo.id}
    

字段少的时候可以接受 ,但是一多就emmm...

2、那么mybatisPlus可以解决这一痛点

mybatis-plus提供了

IService 及其实现类 ServiceImpl, T> 
IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 )

我们在使用时只需继承该实现类即可,前提需要定义继承BaseMapper的Mapper和相应DO

public class DemoServiceImpl extends ServiceImpl {...}

使用:

@Autowired
DemoServiceImpl cpService;

public void mybatisPlusTest() {
    List 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 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 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;
}

 

你可能感兴趣的:(Mybatis)