java / intermediate
Snippet
Executing Bulk Updates with @Modifying and @Query
When performing updates or deletions via JPQL in Spring Data JPA, the @Modifying annotation is required. This informs the framework that the query is an 'execute' operation rather than a 'select', allowing it to properly manage the persistence context.
snippet.java
1
2
3
4
5
6
@Repositorypublic interface UserRepository extends JpaRepository<User, Long> {@Modifying@Query("UPDATE User u SET u.status = :status WHERE u.lastLogin < :date")int updateStatusForInactiveUsers(String status, LocalDateTime date);}
spring
Breakdown
1
@Modifying
Signals that the query modifies the database state (INSERT, UPDATE, or DELETE).
2
@Query("UPDATE User u...")
Defines the custom JPQL statement for the bulk update operation.