MybatisPlus批量更新

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;
}

 

  • 10
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值