Springboot 2.X MongoTemplate 实现批量插入以及批量更新


1 摘要

MongoTemplate 作为 Spring 对 MongoDB 提供的操作类,支持数据的批量操作。本文将介绍使用 MongoTemplate 实现批量插入和批量更新的功能。

2 批量插入

./demo-mongodb/src/main/java/com/ljq/demo/springboot/mongodb/service/impl/BlogServiceImpl.java
    /**
     * 批量新增博客
     *
     * @param addBatchParam
     * @return
     */
    @Override
    public ApiResult addBatch(BlogAddBatchParam addBatchParam) {
        List<BlogEntity> blogEntityList = addBatchParam.getBlogList().stream().map(blogAddParam -> {
            BlogEntity blogEntity = new BlogEntity();
            BeanUtil.copyProperties(blogAddParam, blogEntity);
            return blogEntity;
        }).collect(Collectors.toList());
        mongoTemplate.insert(blogEntityList, BlogEntity.class);
        return ApiResult.success();
    }

批量插入的方法比较简单,MongoTemplate 提供了直接操作的方法。

3 批量更新

./demo-mongodb/src/main/java/com/ljq/demo/springboot/mongodb/service/impl/BlogServiceImpl.java
    /**
     * 批量更新博客
     *
     * @param updateBatchParam
     * @return
     */
    @Override
    public ApiResult updateBatch(BlogUpdateBatchParam updateBatchParam) {
        List<BlogEntity> blogEntityList = updateBatchParam.getBlogList().stream().map(blogUpdateParam -> {
            BlogEntity blogEntity = new BlogEntity();
            BeanUtil.copyProperties(blogUpdateParam, blogEntity);
            return blogEntity;
        }).collect(Collectors.toList());
        BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, BlogEntity.class);
        for (BlogEntity blogEntity : blogEntityList) {
            Update update = Update.update("id", blogEntity.getId())
                    .set("title", blogEntity.getTitle())
                    .set("content", blogEntity.getContent())
                    .set("author", blogEntity.getAuthor())
                    .set("countRead", blogEntity.getCountRead())
                    .set("countLike", blogEntity.getCountLike())
                    .set("clientTimestamp", blogEntity.getClientTimestamp());
            operations.updateOne(Query.query(Criteria.where("id").is(blogEntity.getId())), update);
        }
        operations.execute();
        return ApiResult.success();
    }

批量更新的操作稍微复杂一点,需要针对每个更新的属性进行赋值。

4 推荐参考资料

mongotemplate - Spring数据mongodb批量更新

5 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
404Code

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值