Spring Boot + JPA - CrudRepository update and then read

Viewed 138

I have a scenario where the need is to update some db records first based on a criteria and then read those records from db. I am using CrudReposirtory and in my controller I have a service which calls a repository method using a @Query to update the records and on the next line am trying to read the same records but the records are not updated unless the I am out of that controller method.

1 Answers

You should use @Modifying in conjunction with @Query if you perform an UPDATE statement.

From documentation:

@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);

This will trigger the query annotated to the method as updating query instead of a selecting one. As the EntityManager might contain outdated entities after the execution of the modifying query, we automatically clear it (see JavaDoc of EntityManager.clear() for details). This will effectively drop all non-flushed changes still pending in the EntityManager. If you don't wish the EntityManager to be cleared automatically you can set @Modifying annotation's clearAutomatically attribute to false;

Related