Transactions
transactions (@transactional) spring's @transactional wraps methods in a database transaction — commit on success, rollback on runtime exception. understanding propagation, isolation and
Introduction
Spring's @Transactional wraps methods in a database transaction — commit on success, rollback on runtime exception. Understanding propagation, isolation and rollback rules prevents subtle data corruption bugs.
Informative example
Transactional service method:
@Servicepublic class TransferService {@Transactionalpublic void transfer(Long fromId, Long toId, BigDecimal amount) {Account from = accountRepo.findById(fromId).orElseThrow();Account to = accountRepo.findById(toId).orElseThrow();from.debit(amount);to.credit(amount);// both saves commit together — or both roll back}@Transactional(readOnly = true)public List<Account> listAll() {return accountRepo.findAll();}@Transactional(propagation = REQUIRES_NEW)public void auditLog(String action) { /* separate tx */ }}
Best practices
- Put @Transactional on service layer, not controllers or repositories.
- Self-invocation bypasses the proxy — call through another bean.
- Use readOnly=true for queries — Hibernate skips dirty checking.
Purpose of this lesson
Master Transactions so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Transactions.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when transactions is the right tool for the problem.
Debugging tips
- Changes not persisted? Method is not @Transactional or self-invocation bypassed the proxy.
- Rollback not happening on checked exception? Add rollbackFor = Exception.class.
- LazyInitializationException after return? Transaction closed — fetch inside the tx or use @EntityGraph.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
A payment service we debugged had @Transactional on the controller — moving it to the service layer fixed phantom partial commits.
Interview questions & answers
Q1Explain Transactions in one minute.
Q2When would you avoid Transactions?
Summary
In this lesson you learned Transactions — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.