Spring Data and MongoDB repository - how to create an update query?

旧城冷巷雨未停 提交于 2020-06-27 11:30:15

问题


I have the following jpa repository:

   @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);

Now, i would like to implement a similar update query for a mongoDB repository:

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

But it doesn't work. any references to how a customized mongo repository update looks like?

Thanks


回答1:


The MongoDB query language is a query-only language. Thus, there's no such thing as an update query. If you need to executed dedicated updates with a Spring Data repository on top of MongoDB, you need a custom implementation method.

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

This approach is also described in the reference documentation.




回答2:


If you just pass the previously auto-created _id of the Object with the updated object values, MongoDB 'Update's rather than 'Create' a new instance.



来源:https://stackoverflow.com/questions/24849916/spring-data-and-mongodb-repository-how-to-create-an-update-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!