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.
On this page
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
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@Modifyingis 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
findByStatusAndPriceBetweenAndTeacherNameContainingIgnoreCaseOrderByCreatedAtDescshould 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
@Versionwrap outside the transaction; the error isObjectOptimisticLockingFailureException.
4. Working with AI
Delegate to AI: JPQL/native queries, Specifications for filters, concurrent Testcontainers tests.
Check yourself:
-
@Transactionalmethods arepublic, notfinal, called from another bean. - Business exceptions are unchecked, or have
rollbackFor. - "Check then decrement" uses a conditional UPDATE,
@Versionor@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.
@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
importOneis called throughthis, so there's no transaction: eachsavecommits on its own, and what was saved before validation stays.- Even through the proxy,
InvalidRowExceptionis 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
importOneinto aRowImporterbean with@Transactional(propagation = REQUIRES_NEW, rollbackFor = InvalidRowException.class), validate beforesave. Or use aTransactionTemplateinside 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.addPointsis also@Transactional(REQUIRED) and joinsplaceOrder's transaction. It throws aRuntimeExceptionthrough the proxy, marking the whole transaction rollback-only;placeOrdercatches and logs, but at commit Spring rolls back and throwsUnexpectedRollbackException.- 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: whenaddPointsthrows, the order is still saved.
Summary
- Transactions group steps, they don't queue people; lost updates still happen.
@Transactionalonly 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
@Modifyingbypasses the persistence context; turn off open-in-view.
Further reading: Optimistic and pessimistic locking.
Practice interview questions on this topic
- When do you use derived queries, @Query/JPQL and @Modifying in Spring Data JPA?
- What are the @Transactional pitfalls: self-invocation, checked exceptions, readOnly and timeout?
- What propagation types does @Transactional have? How does REQUIRES_NEW differ from NESTED?
- What is dirty checking? How is flush different from commit?
- When does LazyInitializationException occur? What is open-session-in-view and why turn it off?
- How do you design seat holds/booking so a seat is never sold twice under concurrency?
All JPA & Hibernate questions →All Transactions & Locking questions →All Data Modeling & Scaling questions →All AI & LLM questions →
Comments
Community rules