membersound
membersound

Reputation: 86747

How to update an attribute with spring CrudRepository?

How can I create update methods in spring CurdRepository?

Something like:

interface PersonRepository extends CrudRepository<PersonEntity> {
   //update ... set age =: age where name =: name
   boolean setAgeByName(age, name);
}

Upvotes: 0

Views: 1672

Answers (1)

GHajba
GHajba

Reputation: 3691

If you ask me: do not use such queries. That's because your second level cache gets eradicated and you get some performance problems (your application will be slightly slower).

And by the way the process you want to do is in reality the following:

  • you load your entity from the database
  • change the attribute on the loaded object (via a setter method)
  • you save your entity to the database (this is done automagically when your transaction ends so you do not need to call PartnerRepository.save(entity) explicitly)

If you want to use a query then I suggest you write your query as you mentioned in your question:

@Modifying
@Query("update Person p set p.age = :age where p.name = :name")
int setAgeByName(@Param("age") int age, @Param("name") String name);

And you get back how many entries have been modified.

Upvotes: 1

Related Questions