【问题标题】:Update specific field in mongodb of a spring-boot app using spring-data feature使用 spring-data 功能更新 spring-boot 应用程序的 mongodb 中的特定字段
【发布时间】:2019-01-23 00:06:55
【问题描述】:

我们可以使用 spring-data 功能仅更新 spring-boot 应用程序的 mongodb 中的特定字段吗?

目前,spring-data 提供了一种 save 方法来更新和保存在文档中。如果在一个文档中针对不同字段发生两组并发更新,我们可能会丢失信息。我知道我们可以使用 Mongotemplate 解决问题。我们可以使用 spring-data 解决这些问题吗?

谢谢

【问题讨论】:

    标签: spring spring-boot spring-data spring-data-mongodb mongotemplate


    【解决方案1】:

    在 MongoDB 4.0 中,ACID 事务已到达文档存储,强制执行全有或全无并保持数据完整性。因此,让我们通过查看同步和响应式执行模型来直接了解它。

    你可以这样写代码:

    @Transactional 无效插入文档(){

    operations.insert(documentOne);
    operations.insert(documentTwo);
    

    }

    完成 Spring 的文档:

    https://spring.io/blog/2018/06/28/hands-on-mongodb-4-0-transactions-with-spring-data

    【讨论】:

    • 感谢您的解释。但目前,我使用的是 MongoDB 3.6。有没有针对具体版本的解决方案?谢谢
    【解决方案2】:

    乐观锁定功能怎么样?

    @Version 注释在 MongoDB 上下文中提供类似于 JPA 的语法,并确保更新仅应用于具有匹配版本的文档。因此,版本属性的实际值以这样一种方式添加到更新查询中,即如果同时另一个操作更改了文档,则更新不会产生任何影响。在这种情况下,将引发 OptimisticLockingFailureException。

    请参阅 Spring 文档:https://docs.spring.io/spring-data/mongodb/docs/2.0.9.RELEASE/reference/html/#mongo-template.optimistic-locking

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      相关资源
      最近更新 更多