【问题标题】:Spring Data and MongoDB repository - how to create an update query?Spring Data 和 MongoDB 存储库 - 如何创建更新查询?
【发布时间】:2014-09-11 01:29:39
【问题描述】:

我有以下 jpa 存储库:

   @Query("UPDATE PlayerAccount pa SET pa.password = ?3 WHERE pa.id = ?1 AND pa.password = ?2")
   @Modifying
   public int updatePasswordWithValidation(Long playerAccountId, String oldPasswordDB, String encodePassword);

现在,我想为 mongoDB 存储库实现类似的更新查询:

@Query("update( { _id: ObjectId(' $1 ') }, { $set: { messageStatus: $2} })")

但它不起作用。任何关于自定义 mongo 存储库更新的参考资料?

谢谢

【问题讨论】:

    标签: java spring mongodb spring-data spring-data-mongodb


    【解决方案1】:

    MongoDB 查询语言是一种仅查询语言。因此,没有更新查询之类的东西。如果您需要在 MongoDB 之上使用 Spring Data 存储库执行专用更新,则需要自定义实现方法。

    // Interface for custom functionality
    interface SomeCustomRepository {
      void updateMethod(…);
    }
    
    // Custom implementation
    class FooRepositoryImpl implements SomeCustomRepository {
    
      public void updateMethod(…) {
        mongoTemplate.update(…);
      }
    }
    
    // Core repository declaration combining CRUD functionality and custom stuff
    interface FooRepository extends CrudRepository<Foo, ObjectId>, SomeCustomRepository {
      …
    }
    

    reference documentation 中也描述了这种方法。

    【讨论】:

    【解决方案2】:

    如果您只是将先前自动创建的对象 _id 与更新的对象值一起传递,MongoDB 将“更新”而不是“创建”一个新实例。

    【讨论】:

      猜你喜欢
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 2019-01-29
      • 1970-01-01
      • 2015-12-17
      • 2016-08-29
      • 1970-01-01
      相关资源
      最近更新 更多