Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 840
Urbanleg Avatar asked Feb 12 '23 11:02

Urbanleg


1 Answers

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.

like image 127
Oliver Drotbohm Avatar answered Feb 15 '23 01:02

Oliver Drotbohm