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

5

我有以下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存储库更新的参考资料在哪里?谢谢。
2个回答

10

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 {
  …
}

该方法也在参考文档中描述。


嘿,Oliver,链接是404。 - Madbreaks
@Madbreaks 这是特定版本的更新:https://docs.spring.io/spring-data/mongodb/docs/2.2.5.RELEASE/reference/html/#repositories.single-repository-behavior - Sebastian

-1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接