SteelReed

Search

Search posts, questions…

4. Database & SQL

ORM and JPA: JPQL, native queries, @Transactional and locking

Where derived queries fall short, JPQL and native queries with @Query and @Modifying, dynamic queries, @Transactional pitfalls, optimistic vs pessimistic locking and open-session-in-view.

17 Nov 20269 min readSenior

–

1. The problem

A 100-seat course opens at 9:00; at 9:01 the enrollments table has 103 rows. enroll is @Transactional, reads seatsLeft, subtracts 1, saves; the single-threaded test is green. The next day's fix calls the method through this, and from then on there's no transaction at all.

2. Key idea

A transaction gives "all or nothing", not "one at a time". Two transactions both reading seats_left = 1 and both writing 0 is a lost update, in every ORM and every DB at the default isolation.

Failure Symptom Root cause
Lost update overselling, wrong balances read in the app, then write a precomputed value
Self-invocation @Transactional seems absent called through this, not the proxy
Checked exception a business error, yet data is written by default only RuntimeException/Error roll back
UnexpectedRollbackException the outer method "caught it" and still fails an inner REQUIRED method marked it rollback-only

2.1 What guards the invariant, what runs the query?

Tool Use when Don't use when
Conditional UPDATE (where seatsLeft > 0) a simple single-row operation you need entity logic, callbacks, @Version
@Version (optimistic) rare conflicts, forms edited across requests hot rows: thousands reserving at once
FOR UPDATE (pessimistic) frequent conflicts, multi-step logic locking many rows in no fixed order
JPQL @Query fixed joins and group-bys (written against entity names) window functions, upserts
Native @Query DB-specific features no integration test on the real DB
Specification dynamic filters fixed queries

Three rules for @Transactional: put it on public methods of a service bean, called from another bean; make business errors unchecked or declare rollbackFor; keep only SQL inside.

3. In Java

JAVA
public interface CourseRepository extends JpaRepository<Course, Long> {
    @Modifying                                     // one statement, the DB locks the row briefly
    @Query("update Course c set c.seatsLeft = c.seatsLeft - 1 where c.id = :id and c.seatsLeft > 0")
    int takeSeat(@Param("id") Long id);            // 0 = full
 
    @Lock(LockModeType.PESSIMISTIC_WRITE)          // SELECT ... FOR UPDATE
    @Query("select c from Course c where c.id = :id")
    Optional<Course> findForUpdate(@Param("id") Long id);
}
 
@Service
class EnrollmentService {                          // called from a controller, through the proxy
    @Transactional                                 // business exceptions are unchecked
    public void enroll(long courseId, long studentId) {
        if (courseRepository.takeSeat(courseId) == 0) throw new CourseFullException(courseId);
        enrollmentRepository.saveAndFlush(new Enrollment(studentId, courseId)); // unique (student, course)
    }
}

Other languages: Django has select_for_update() and F('seats') - 1; EF Core has RowVersion and ExecuteUpdate.

Bulk updates, JPQL and open-session-in-view
  • Load-then-modify keeps validation, @Version, @PreUpdate, cascades and auditing, but 10,000 rows means 10,000 entities. Bulk @Modifying is one SQL statement but skips all of that, and entities already in the persistence context go stale: use @Modifying(clearAutomatically = true, flushAutomatically = true).
  • JPQL queries entity names and fields (select u from User u), not tables; interface projections (getTeacherName()) keep results lean. Bind every parameter; map dynamic sorting from a whitelist.
  • Derived queries with names like findByStatusAndPriceBetweenAndTeacherNameContainingIgnoreCaseOrderByCreatedAtDesc should become @Query.
  • Open-session-in-view (on by default in Boot) keeps the session open through rendering: lazy queries fire from controllers and the connection is held for the whole request. Set spring.jpa.open-in-view=false.
  • Retries for @Version wrap outside the transaction; the error is ObjectOptimisticLockingFailureException.

4. Working with AI

Delegate to AI: JPQL/native queries, Specifications for filters, concurrent Testcontainers tests.

Check yourself:

  • @Transactional methods are public, not final, called from another bean.
  • Business exceptions are unchecked, or have rollbackFor.
  • "Check then decrement" uses a conditional UPDATE, @Version or @Lock, not read-then-save.
  • A test fires 20 concurrent requests at a course with 5 seats left: exactly 5 enrollments.

5. Exercises

Exercise 1: Review an import with "one transaction per row"

AI's description: "each row gets its own transaction via REQUIRES_NEW, a bad row rolls back without affecting others". Importing 1,000 rows with row 500 invalid leaves a partial record of row 500 in the DB. Find the bugs, name a test, fix it.

JAVA
@Service
public class ImportService {
    public void importAll(List<Row> rows) {
        for (Row r : rows) {
            try { importOne(r); } catch (InvalidRowException e) { log.warn("skip {}", r, e); }
        }
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void importOne(Row r) throws InvalidRowException { ... }  // saves, then validates
}
Solution to Exercise 1
  • importOne is called through this, so there's no transaction: each save commits on its own, and what was saved before validation stays.
  • Even through the proxy, InvalidRowException is checked, so it commits by default.
  • Test: import 3 rows with row 2 invalid; the DB has exactly 2 rows and nothing from row 2.
  • Fix: move importOne into a RowImporter bean with @Transactional(propagation = REQUIRES_NEW, rollbackFor = InvalidRowException.class), validate before save. Or use a TransactionTemplate inside the loop.

Exercise 2: Read an UnexpectedRollbackException incident

After adding loyalty points, order failures (500s) rise from 0.1% to 4%, matching the rate of failed point awards. Log: UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only from OrderService.placeOrder, right after WARN loyalty failed. Diagnose, act within 15 minutes, fix the root cause.

Solution to Exercise 2
  • loyaltyService.addPoints is also @Transactional (REQUIRED) and joins placeOrder's transaction. It throws a RuntimeException through the proxy, marking the whole transaction rollback-only; placeOrder catches and logs, but at commit Spring rolls back and throws UnexpectedRollbackException.
  • 15 minutes: switch off loyalty points with a feature flag; search logs for rolled-back orders to contact customers.
  • Root fix: points must never break an order: publish an event handled by @TransactionalEventListener(AFTER_COMMIT) or an outbox. Test: when addPoints throws, the order is still saved.

Summary

  • Transactions group steps, they don't queue people; lost updates still happen.
  • @Transactional only works through the proxy; checked exceptions commit by default.
  • One row: a conditional UPDATE; rare conflicts: @Version; hot multi-step rows: FOR UPDATE.
  • JPQL for fixed joins, Specifications for dynamic filters.
  • Bulk @Modifying bypasses the persistence context; turn off open-in-view.

Further reading: Optimistic and pessimistic locking.

Practice interview questions on this topic

All JPA & Hibernate questions →All Transactions & Locking questions →All Data Modeling & Scaling questions →All AI & LLM questions →

Loading comments…
Next on the roadmapCron jobs: cron expressions and @Scheduled in Spring Boot