Spring Data和MongoDB存储库 - 如何创建更新查询?

问题描述 投票:3回答:2

我有以下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
2个回答
6
投票

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中描述。


0
投票

如果您只是使用更新的对象值传递先前自动创建的Object的_id,则MongoDB'Update'而不是'Create'一个新实例。

© www.soinside.com 2019 - 2024. All rights reserved.