Video in progress

What can go wrong after this bulk UPDATE, and what rule do you set in the team for such queries?

@Transactional
public void expireOld() {
    List<Coupon> active = couponRepo.findActive();      // 1
    couponRepo.expireOlderThan(LocalDate.now());          // bulk UPDATE
    active.forEach(c -> log.info("{} {}", c.getId(), c.getStatus())); // 2
    active.get(0).setNote("tekshirildi");                 // 3
}

A bulk JPQL goes straight to the database: entities in the persistence context and the L2 cache go stale, @Version does not increase, and entity listeners do not run. The rule: clear the context after a bulk operation, and keep such methods separate and documented.

📖 Answer

On line 1 the coupons were loaded into the persistence context. The bulk UPDATE set status = EXPIRED in the database, but the objects in memory don't know it. Line 2 logs the old status. The change on line 3 becomes an UPDATE at flush, and if Hibernate writes all columns (the default, without @DynamicUpdate), it also writes status back to its old value. The bulk change was silently undone.

What else gets bypassed:

  • @Version: a bulk UPDATE does not increase the version, unless you use the update versioned syntax or write version = version + 1 by hand;
  • @PreUpdate, Envers auditing, @UpdateTimestamp do not run;
  • the L2 cache: after a bulk query Hibernate evicts the whole region for that entity, which for a big cache means an unexpected storm of cache misses.

Protection in Spring Data:

@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query("update Coupon c set c.status = 'EXPIRED' where c.validTo < :d")
int expireOlderThan(@Param("d") LocalDate d);

flushAutomatically doesn't lose earlier changes, and clearAutomatically throws out the stale entities. But after the clear, the entities you are holding become detached, so the change on line 3 is no longer saved at all.

Team rule: bulk methods live in a separate service and a separate transaction, with no other entity work inside. If they touch tables that need auditing, adding the audit record by hand is mandatory.