Transactions
@Transactional defines the atomic unit of work for Orders: reserve inventory, insert the order, write outbox events — all commit together or roll back together.
Introduction
@Transactional defines the atomic unit of work for Orders: reserve inventory, insert the order, write outbox events — all commit together or roll back together. On Boot 3, Spring's proxy-based transaction manager coordinates the JPA persistence context and the JDBC connection.
Place transactions on the service layer. Repository methods participate in the existing transaction. Self-invocation inside the same class bypasses the proxy — transactional advice never runs for that call.
Defaults roll back on unchecked exceptions. Checked exceptions need rollbackFor. Use readOnly = true for query paths to hint the driver and skip dirty checking. REQUIRES_NEW is for independent side effects (audit) that must commit even if the outer work fails — use sparingly.
Correctness under concurrency may need locking (PESSIMISTIC_WRITE or optimistic @Version) when two checkouts touch the same stock row.
Purpose of this lesson
Apply Spring @Transactional correctly on Orders services — boundaries, rollback rules, readOnly, and proxy pitfalls.
Understanding the topic
Transactions are service-level consistency tools.
- proxy AOP: external calls get advice; self-calls do not.
- rollback: runtime by default; configure checked exceptions explicitly.
- readOnly: optimize pure reads.
- propagation: REQUIRED joins; REQUIRES_NEW suspends.
- locking: pessimistic/optimistic when races matter.
Step-by-step explanation
- Annotate
OrderServiceplace/cancel methods with@Transactional. - Mark list/get methods
readOnly = true. - Demonstrate a self-invocation bug; extract a collaborator bean to fix it.
- Add rollback on a domain checked exception if your API uses one.
Informative example
Orders service transaction boundaries.
@Servicepublic class OrderService {private final OrderRepository orders;private final InventoryClient inventory;public OrderService(OrderRepository orders, InventoryClient inventory) {this.orders = orders;this.inventory = inventory;}@Transactional(readOnly = true)public OrderView get(long id) {return orders.findById(id).map(OrderView::from).orElseThrow(() -> new OrderNotFoundException(id));}@Transactional(rollbackFor = Exception.class)public OrderView place(CreateOrderRequest req) {if (!inventory.reserve(req.sku(), req.qty())) {throw new IllegalStateException("out of stock");}Order saved = orders.save(Order.from(req));return OrderView.from(saved);}}
Real-world use
Place-order must not leave reserved stock without an order row, or an order row without a reservation. One service transaction (plus careful inventory semantics) keeps TechLearningPRO checkout consistent when the payment step fails and rolls back.
Security implications
Failed security checks must not partially commit.
- Authorize before mutating; throw so the transaction rolls back.
- Do not commit orders the caller is not allowed to place.
- Avoid logging full order payloads inside transactional retries.
Best practices
- Keep transactions short; do external I/O outside when possible (or use outbox patterns).
- Prefer service-level boundaries over repository-level transactions.
- Use
readOnly = trueon query methods.
Common mistakes
- Putting
@Transactionalonly on private methods or self-calls. - Catching exceptions inside the transactional method and swallowing them so rollback never happens.
- Long transactions that call slow HTTP APIs while holding DB connections.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhere should @Transactional live in a Boot app?+
Answer
2IntermediateQuestionWhy can self-invocation skip transactional advice?+
Answer
this.method() never enters the proxy.3IntermediateQuestionWhat does readOnly=true do?+
Answer
Hands-on exercise
Lab. Implement place so a forced inventory failure rolls back the insert. Then call a transactional method via this. from another method in the same class and show it does not open a transaction — fix by injecting self or splitting beans.
Summary
Transactions make multi-step Orders writes atomic. Next: optimize the database access patterns that dominate latency.