Video in progress

Junior 🌱 Spring

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:

  1. Transaction. The repository's default methods are transactional, but your @Query method may run in a read-only transaction or none at all. Put @Transactional on the service method or the repository method, otherwise you get TransactionRequiredException.
  2. Stale cache. A bulk UPDATE bypasses the persistence context. If Account objects are already in memory in the same transaction, they show the old value. clearAutomatically = true clears the context.
  3. The lifecycle is bypassed. @PreUpdate, @Version increments 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.