java 18 lines · 5 steps

Bulk JPQL updates in a Spring Data repository

A Spring Data repository runs set-based UPDATE statements directly against the database instead of loading and saving entities one by one.

Explained by highlit
1@Repository
2public interface SubscriptionRepository extends JpaRepository<Subscription, Long> {
3 
4 @Modifying(clearAutomatically = true, flushAutomatically = true)
5 @Query("""
6 UPDATE Subscription s
7 SET s.status = :status,
8 s.deactivatedAt = :now
9 WHERE s.status = com.acme.billing.SubscriptionStatus.ACTIVE
10 AND s.currentPeriodEnd < :now
11 """)
12 int expireOverdueSubscriptions(@Param("status") SubscriptionStatus status,
13 @Param("now") Instant now);
14 
15 @Modifying
16 @Query("UPDATE Subscription s SET s.reminderSent = true WHERE s.id IN :ids")
17 int markRemindersSent(@Param("ids") Collection<Long> ids);
18}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Bulk JPQL updates run set-based SQL in one round trip, bypassing per-entity loading entirely.
  2. 2Because bulk updates skip the persistence context, clearing and flushing keeps in-memory entities from going stale.
  3. 3A modifying query returns the affected row count, giving you a cheap signal of how much work happened.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Bulk JPQL updates in a Spring Data repository — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code