Video in progress
Why does an update or delete @Query in Spring Data JPA need @Modifying?
By default Spring Data assumes @Query is a SELECT. @Modifying tells it "this is an UPDATE or DELETE", and the query goes through executeUpdate. There's one more requirement: a transaction.
📖 Answer
public interface AccountRepository extends JpaRepository<Account, Long> {
@Modifying(clearAutomatically = true)
@Transactional
@Query("update Account a set a.status = :status where a.lastLogin < :before")
int deactivateOld(@Param("status") Status status, @Param("before") Instant before);
}
Without @Modifying, Spring Data expects a result list from the query and fails with Not supported for DML operations or something similar.
Three more points:
- Transaction. The repository's default methods are transactional, but your
@Querymethod may run in a read-only transaction or none at all. Put@Transactionalon the service method or the repository method, otherwise you getTransactionRequiredException. - Stale cache. A bulk UPDATE bypasses the persistence context. If
Accountobjects are already in memory in the same transaction, they show the old value.clearAutomatically = trueclears the context. - The lifecycle is bypassed.
@PreUpdate,@Versionincrements and auditing don't run, because the entities aren't loaded.
The returned int is the number of rows changed. It's useful to log it.
Sign up to mark studied questions and save your progress.