Transactions with @Transactional
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer orders three items. If the third item fails after stock was already reduced, the shop is left with missing stock and an order without items. An order must be saved completely or not at all.
Placing an order: insert order, insert items, reduce stock in one transaction
A transaction is a group of SQL statements that the database treats as one. Commit saves all of them; rollback undoes all of them.
Placing a ShopLite order changes three tables: it takes stock in products, adds a row to orders and adds rows to order_items. Plain JDBC runs in auto-commit mode.
Example 1 · OrderLabService.java: three writes for one order
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
package com.shoplite.lab;
import org.springframework.dao.DataAccessException;import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
/** * Three writes for one order: take stock of product 9 (Clean Code), insert the order, insert its item. * The item insert uses the product id it is given, so productId 99 fails on the foreign key. */@Servicepublic class OrderLabService {
private final JdbcClient jdbc;
OrderLabService(JdbcClient jdbc) { this.jdbc = jdbc; }
/** No transaction: every statement commits on its own (auto-commit). */ public void placeWithoutTransaction(long itemProductId) { writeOrder(itemProductId); }
/** One transaction: all three writes commit together, or none of them. */ @Transactional public void placeInTransaction(long itemProductId) { writeOrder(itemProductId); }
/** A checked exception after the writes: by default Spring COMMITS. */ @Transactional public void placeThenPaymentFails() throws PaymentFailedException { writeOrder(9); throw new PaymentFailedException("UPI payment declined"); }
/** The fix: rollbackFor makes checked exceptions roll back too. */ @Transactional(rollbackFor = Exception.class) public void placeThenPaymentFailsFixed() throws PaymentFailedException { writeOrder(9); throw new PaymentFailedException("UPI payment declined"); }
/** The self-invocation trap: this.placeInTransaction(...) skips the proxy, so there is no transaction. */ public void placeViaSelfCall(long itemProductId) { this.placeInTransaction(itemProductId); }
/** readOnly: fine for queries, but MySQL refuses any write inside it. */ @Transactional(readOnly = true) public void placeInReadOnlyTransaction() { writeOrder(9); }
/** The swallow trap: the exception never leaves the method, so Spring sees success and COMMITS. */ @Transactional public void placeSwallowingError(long itemProductId) { try { writeOrder(itemProductId); } catch (DataAccessException e) { System.out.println(" error caught and ignored: " + e.getClass().getSimpleName()); } }
private void writeOrder(long itemProductId) { int taken = jdbc.sql("UPDATE products SET stock = stock - 1 WHERE product_id = 9 AND stock >= 1").update(); System.out.println(" stock taken: " + taken + " row"); jdbc.sql("INSERT INTO orders (customer_id, address_id, status) VALUES (1, 1, 'PLACED')").update(); System.out.println(" order row inserted"); long orderId = jdbc.sql("SELECT LAST_INSERT_ID()").query(Long.class).single(); jdbc.sql("INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, 1, 499.00)") .params(orderId, itemProductId) .update(); System.out.println(" item row inserted"); }}$ java -jar target/jdbc-lab-0.1.0.jar tx-none == tx-none before: Clean Code stock = 30, orders = 16 stock taken: 1 row order row inserted failed: DataIntegrityViolationException after : Clean Code stock = 29, orders = 17
What this code does
placeWithoutTransactionhas no@Transactional, so each statement commits at once. The item insert fails on the foreign key (product 99), but the stock change and the order row are already saved.- After the failure: Clean Code stock 29 and 17 orders, one of them with no items. This is exactly the broken state a transaction prevents.
- The other methods of this class are used in the next examples and in the practice tasks.
In auto-commit mode every statement is saved the moment it finishes. In the example, stock is taken and the order row is saved, then the item insert fails (product 99 does not exist). The first two changes stay: Clean Code lost one unit and the shop has an order with no items.
In Section 13 you fixed this by hand: setAutoCommit(false), commit(), rollback() in a catch, and the same Connection passed to every DAO. Spring does all of that for you, as the next section shows.
@Transactional on the service method, and rollback on runtime exceptions
@Transactional on a public method of a Spring bean tells Spring to start a transaction before the method, commit after it returns and roll back if it throws a runtime exception.
Every JdbcClient call inside the method uses the same connection, so all its statements belong to one transaction. The DEBUG log shows each step.
Example 2 · TransactionDemo.java: run a demo and print stock and order count
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
package com.shoplite.lab;
import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.stereotype.Component;
/** java -jar jdbc-lab.jar tx-none | tx-on | tx-checked | tx-checked-fixed | tx-self | tx-self-fixed | tx-readonly | tx-swallow */@Componentclass TransactionDemo implements ApplicationRunner {
private final OrderLabService service; private final CheckoutService checkout; private final JdbcClient jdbc;
TransactionDemo(OrderLabService service, CheckoutService checkout, JdbcClient jdbc) { this.service = service; this.checkout = checkout; this.jdbc = jdbc; }
@Override public void run(ApplicationArguments args) { for (String demo : args.getNonOptionArgs()) { if (!demo.startsWith("tx-")) { continue; } System.out.println("== " + demo); print("before"); try { switch (demo) { case "tx-none" -> service.placeWithoutTransaction(99); case "tx-on" -> service.placeInTransaction(99); case "tx-checked" -> service.placeThenPaymentFails(); case "tx-checked-fixed" -> service.placeThenPaymentFailsFixed(); case "tx-self" -> service.placeViaSelfCall(99); case "tx-self-fixed" -> checkout.placeOrder(99); case "tx-readonly" -> service.placeInReadOnlyTransaction(); case "tx-swallow" -> service.placeSwallowingError(99); default -> System.out.println("unknown demo"); } } catch (Exception e) { System.out.println(" failed: " + e.getClass().getSimpleName()); if (demo.equals("tx-readonly")) { System.out.println(" cause: " + e.getCause().getMessage()); } } print("after "); } }
private void print(String when) { int stock = jdbc.sql("SELECT stock FROM products WHERE product_id = 9").query(Integer.class).single(); int orders = jdbc.sql("SELECT COUNT(*) FROM orders").query(Integer.class).single(); System.out.println(when + ": Clean Code stock = " + stock + ", orders = " + orders); }}$ java -jar target/jdbc-lab-0.1.0.jar tx-on --logging.level.org.springframework.jdbc.support.JdbcTransactionManager=DEBUG == tx-on before: Clean Code stock = 30, orders = 16 DEBUG o.s.jdbc.support.JdbcTransactionManager : Creating new transaction with name [com.shoplite.lab.OrderLabService.placeInTransaction]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.jdbc.support.JdbcTransactionManager : Acquired Connection [HikariProxyConnection@... wrapping ConnectionImpl@...] for JDBC transaction DEBUG o.s.jdbc.support.JdbcTransactionManager : Switching JDBC Connection [HikariProxyConnection@... wrapping ConnectionImpl@...] to manual commit stock taken: 1 row order row inserted DEBUG o.s.jdbc.support.JdbcTransactionManager : Initiating transaction rollback DEBUG o.s.jdbc.support.JdbcTransactionManager : Rolling back JDBC transaction on Connection [HikariProxyConnection@... wrapping ConnectionImpl@...] DEBUG o.s.jdbc.support.JdbcTransactionManager : Releasing JDBC Connection [HikariProxyConnection@... wrapping ConnectionImpl@...] after transaction failed: DataIntegrityViolationException after : Clean Code stock = 30, orders = 16
What this code does
- The demo calls
service.placeInTransaction(99)on the injected bean, so the call goes through the proxy: "Creating new transaction" appears before the first SQL statement. - The connection switches to manual commit, the item insert throws
DataIntegrityViolationException(unchecked), and the proxy rolls back. Stock is 30 and orders 16 again: nothing happened.
Spring does this with a proxy: the object other beans receive is a generated wrapper around your service. The wrapper begins the transaction, calls your real method, then commits or rolls back.
Put @Transactional on service methods, the ones that describe one business action ("place an order"). A repository method is one statement and needs none of its own; a controller should not know transactions exist. When place() calls productService.takeStock(...), which is also @Transactional, the inner call joins the running transaction (the default propagation, REQUIRED).
Checked exceptions do not roll back by default
A checked exception is one the compiler makes you declare with throws. By default Spring does not roll back for it: the transaction commits what was done so far.
By default Spring rolls back only for unchecked exceptions: RuntimeException, its subclasses and Error. A checked exception leaves the work saved.
Example 3 · A checked exception commits; rollbackFor fixes it
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
java -jar target/jdbc-lab-0.1.0.jar tx-checkedjava -jar target/jdbc-lab-0.1.0.jar tx-checked-fixed$ java -jar target/jdbc-lab-0.1.0.jar tx-checked == tx-checked before: Clean Code stock = 30, orders = 16 stock taken: 1 row order row inserted item row inserted failed: PaymentFailedException after : Clean Code stock = 29, orders = 17 $ java -jar target/jdbc-lab-0.1.0.jar tx-checked-fixed == tx-checked-fixed before: Clean Code stock = 30, orders = 16 stock taken: 1 row order row inserted item row inserted failed: PaymentFailedException after : Clean Code stock = 30, orders = 16
What this code does
placeThenPaymentFails()is@Transactionaland fails, yet stock is 29 and there are 17 orders: Spring committed, becausePaymentFailedExceptionis checked.placeThenPaymentFailsFixed()has@Transactional(rollbackFor = Exception.class), so the same failure rolls back to 30 and 16.
The rule comes from the idea that a checked exception is an expected business outcome, not a failure. That surprises many developers: in the example, placeThenPaymentFails() writes the order and then throws PaymentFailedException, a checked exception, so the stock and the order stay saved although the method failed.
There are two fixes. Add rollbackFor = Exception.class to the annotation, or, as ShopLite does, make business exceptions unchecked: every ShopLiteException extends RuntimeException, so any of them rolls back.
Predict the output
Saved or rolled back?
Each method inserts an order, then throws. Pick what happens to the order row.
Round 1 of 3
PaymentFailedException is a checked exception. Is the order saved?
The self-invocation trap: calling a @Transactional method from the same class
Self-invocation means a method calls another method of the same object, such as this.placeInTransaction(...). The call skips the proxy, so @Transactional on the called method is ignored.
Spring can start a transaction only when a call passes through the proxy. In this.method(), this is the real object, so every statement auto-commits.
Example 4 · CheckoutService.java: the self-invocation trap and its fix
Runs in: a small Spring Boot lab project (JDBC starter, MySQL driver) on the ShopLite database
package com.shoplite.lab;
import org.springframework.stereotype.Service;
/** The self-invocation fix: call the @Transactional method from ANOTHER bean, so the call goes through the proxy. */@Servicepublic class CheckoutService {
private final OrderLabService orders;
CheckoutService(OrderLabService orders) { this.orders = orders; }
public void placeOrder(long itemProductId) { orders.placeInTransaction(itemProductId); // through the proxy: a real transaction }}$ java -jar target/jdbc-lab-0.1.0.jar tx-self == tx-self before: Clean Code stock = 30, orders = 16 stock taken: 1 row order row inserted failed: DataIntegrityViolationException after : Clean Code stock = 29, orders = 17 $ java -jar target/jdbc-lab-0.1.0.jar tx-self-fixed == tx-self-fixed before: Clean Code stock = 30, orders = 16 stock taken: 1 row order row inserted failed: DataIntegrityViolationException after : Clean Code stock = 30, orders = 16
What this code does
tx-selfcallsplaceViaSelfCall, which has no annotation and callsthis.placeInTransaction(99). The call skips the proxy, so no transaction starts and the partial order stays (29, 17).tx-self-fixedgoes throughCheckoutService, another bean. Its call toorders.placeInTransaction(99)passes the proxy, so the failure rolls back (30, 16).
The same proxy rule explains two cousins of this bug: @Transactional on a private method does nothing, and an object you create with new is not a proxy at all.
The fix is to make the call go through a bean: put @Transactional on the method that is called from outside, or move the transactional method into another bean and inject it. ShopLite's OrderService calls productService.takeStock(...) on another bean, so the proxy is always involved.
Find the bug
Why is there no transaction?
Click the line that stops the transaction from working.
A controller calls checkout(). Which line skips the proxy?
Round 1 of 2readOnly for queries and a race-safe stock update (UPDATE ... WHERE stock >= ?)
A race condition happens when two requests read the same value and both act on it, so the result depends on timing.
@Transactional(readOnly = true) marks a transaction that only reads, and MySQL then refuses any write in it. ShopLite puts it on each service class and adds a plain @Transactional on the methods that write.
Example 5 · ShopLite: readOnly by default and the race-safe stock update
Runs in: the shoplite-api Spring Boot project with the ShopLite MySQL database
// src/main/java/com/shoplite/order/OrderService.java (parts)@Service@Transactional(readOnly = true)public class OrderService {
@Transactional public OrderResponse place(PlaceOrderRequest request) { /* ... customer, address and product checks (422), early stock check (409) ... */
/* Take stock in product id order, so two orders always lock rows in the same order (no deadlock) */ request.items().stream() .sorted(Comparator.comparing(OrderItemRequest::productId)) .forEach(item -> productService.takeStock(products.get(item.productId()), item.quantity()));
/* ... insert the order row and one row per item, then build the response ... */ }}
// src/main/java/com/shoplite/product/ProductService.java (part)@Transactionalpublic void takeStock(ProductForOrder product, int quantity) { if (!repository.decreaseStock(product.id(), quantity)) { int available = repository.findById(product.id()).map(Product::getStock).orElse(0); throw new OutOfStockException(product.id(), product.name(), available, quantity); } /* ... low-stock warning ... */}
// src/main/java/com/shoplite/product/JdbcProductRepository.java (part)public boolean decreaseStock(Long id, int quantity) { /* Check and change in ONE statement: two buyers can never both take the last unit */ int rows = jdbc.sql("UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?") .params(quantity, id, quantity) .update(); return rows == 1;}$ curl -s -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":2,"addressId":3,"items":[{"productId":9,"quantity":1},{"productId":3,"quantity":9}]}'
{"type":"https://shoplite.example/problems/out-of-stock","title":"Not enough stock","status":409,"detail":"Only 8 units of iPhone 15 128GB are in stock; 9 were requested.","instance":"/api/v1/orders","productId":3,"available":8,"requested":9}
$ curl -s http://localhost:8080/api/v1/products/9
{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}
$ curl -s http://localhost:8080/api/v1/products/3
{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}
$ curl -s -X POST http://localhost:8080/api/v1/orders -H "Content-Type: application/json" -d '{"customerId":1,"addressId":1,"items":[{"productId":9,"quantity":1},{"productId":6,"quantity":2}]}'
{"id":17,"customerId":1,"addressId":1,"status":"PLACED","orderedAt":"2026-10-16T12:15:56+05:30","items":[{"productId":9,"sku":"BK-CLEAN","productName":"Clean Code","quantity":1,"unitPrice":499.00,"lineTotal":499.00},{"productId":6,"sku":"ACC-AD141","productName":"boAt Airdopes 141","quantity":2,"unitPrice":1299.00,"lineTotal":2598.00}],"total":3097.00}
$ curl -s http://localhost:8080/api/v1/products/9
{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":29,"isActive":true}
$ mvn verify (OrderServiceIT includes "two buyers cannot both get the last units")
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.757 s -- in com.shoplite.order.OrderServiceITWhat this code does
- The first order asks for 9 iPhones while only 8 exist: 409 out-of-stock, and Clean Code (the other item) still has 30, the iPhone 8. The second order succeeds and Clean Code drops to 29.
OrderServiceITstarts two threads that each try to buy the last 3 HP laptops at the same moment: one gets PLACED, the other out-of-stock, and stock ends at 0, never below.
If two students each see "8 iPhones left" and both buy 8, a "read stock, check, then write" design sells 16. ShopLite checks and changes in one statement: UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?. MySQL locks the row while it runs, so the second buyer's update sees the new stock, matches no row and returns 0. The service turns 0 into OutOfStockException, and the transaction rolls back everything that order did.
Spring tells the JDBC driver about readOnly, which can skip some bookkeeping (a write in it fails with "Connection is read-only"). Items are updated in product-id order: two orders that lock the same rows always lock them in the same order, so they cannot wait for each other forever (a deadlock).
Next step
Check your understanding
12 quick questions