@Transactional on service methods
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer pays for two items. The first is taken from stock, then the second is sold out. Without protection, the first unit is gone and no order exists. ShopLite needs the whole checkout to succeed or fail as one.
ACID and the proxy around a @Transactional method
A transaction is a group of database changes that are saved together or not at all. In Spring you get one by putting @Transactional on a public method of a bean.
Put @Transactional on a method and Spring runs it inside one transaction. First a tiny model of what Spring does around the method, then a real service and its log.
Example 1 · ProxyModelDemo.java: a tiny model of the transaction proxy
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Proxy;
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface Tx {}
interface FeeService { @Tx void payFee(String rollNo, int amount);}
class RealFeeService implements FeeService { @Override public void payFee(String rollNo, int amount) { System.out.println(" UPDATE students SET fee_paid = fee_paid + " + amount + " WHERE roll_no = '" + rollNo + "'"); if (amount > 50_000) { throw new IllegalArgumentException("Amount above the per-payment limit"); } System.out.println(" INSERT INTO receipts ..."); }}
public class ProxyModelDemo {
// A tiny model of what Spring's proxy does around a @Transactional method static FeeService withTransactions(FeeService target) { return (FeeService) Proxy.newProxyInstance( FeeService.class.getClassLoader(), new Class<?>[] {FeeService.class}, (proxy, method, args) -> { Method declared = FeeService.class.getMethod(method.getName(), method.getParameterTypes()); if (!declared.isAnnotationPresent(Tx.class)) { return method.invoke(target, args); } System.out.println("BEGIN"); try { Object result = method.invoke(target, args); System.out.println("COMMIT"); return result; } catch (InvocationTargetException e) { System.out.println("ROLLBACK because " + e.getCause().getMessage()); throw e.getCause(); } }); }
public static void main(String[] args) { FeeService service = withTransactions(new RealFeeService()); System.out.println("Caller holds a " + (Proxy.isProxyClass(service.getClass()) ? "proxy" : "plain object"));
service.payFee("21CS042", 45_000); try { service.payFee("21CS043", 60_000); } catch (IllegalArgumentException e) { System.out.println("Caller sees: " + e.getMessage()); } }}Caller holds a proxy BEGIN UPDATE students SET fee_paid = fee_paid + 45000 WHERE roll_no = '21CS042' INSERT INTO receipts ... COMMIT BEGIN UPDATE students SET fee_paid = fee_paid + 60000 WHERE roll_no = '21CS043' ROLLBACK because Amount above the per-payment limit Caller sees: Amount above the per-payment limit
What this code does
- A simplified model with a JDK dynamic proxy, not Spring itself: the caller holds the wrapper, and the wrapper prints BEGIN before the real method and COMMIT or ROLLBACK after it.
- Spring builds a similar wrapper (a CGLIB subclass) for every bean with
@Transactionalmethods, and talks to the real database instead of printing.
Example 2 · RestockService.java: one @Transactional method and its log
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/basics/RestockService.javapackage com.shoplite.lab.basics;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class RestockService {
private final ProductRepository products;
public RestockService(ProductRepository products) { this.products = products; }
@Transactional public int restock(int productId, int units) { Product product = products.findById(productId).orElseThrow(); product.setStock(product.getStock() + units); // dirty checking writes the UPDATE at commit return product.getStock(); }}
// src/main/java/com/shoplite/lab/basics/RestockDemo.javapackage com.shoplite.lab.basics;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("restock")public class RestockDemo implements LabDemo {
private final RestockService restockService; private final LabDb db;
public RestockDemo(RestockService restockService, LabDb db) { this.restockService = restockService; this.db = db; }
@Override public void run() { System.out.println("Injected bean: " + restockService.getClass().getSimpleName()); System.out.println("Stock of product 9 before: " + db.stock(9)); int newStock = restockService.restock(9, 20); System.out.println("restock returned " + newStock + ", stock in MySQL now: " + db.stock(9)); }}$ java -jar target/tx-lab-0.1.0.jar --demo=restock Injected bean: RestockService$$SpringCGLIB$$0 Stock of product 9 before: 30 DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.basics.RestockService.restock]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1406632624<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@24bf95ec] DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(1406632624<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(1406632624<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction restock returned 50, stock in MySQL now: 50
What this code does
- The injected class name contains
SpringCGLIB: it is the proxy subclass Spring generated, notRestockServiceitself. The log shows it begin a transaction named after the method, then commit afterrestockreturned. findByIdinside loggedParticipating in existing transaction: the repository joined the service transaction. The stock change was written by dirty checking at commit, without anysave().
Section 13 called setAutoCommit(false), commit() and rollback() by hand, and Section 15 met @Transactional with JdbcClient. A transaction promises ACID: atomic (all or nothing), consistent (rules such as stock ≥ 0 hold afterwards), isolated (other users do not see half-done work) and durable (a commit survives a crash).
Spring does not change your class. Other beans receive a proxy, a generated subclass that begins the transaction, calls your method, then commits or rolls back. With JPA, every repository call inside the method shares one EntityManager, and dirty checking writes the changes at commit.
Order of execution
The proxy around your method
Tap the steps in the order they happen.
--demo=<name>. Every demo starts from a freshly loaded ShopLite database.Put @Transactional on services, not controllers or repositories
A controller only turns HTTP into calls, and a repository handles one table, so the service method is the place for the transaction. The next example runs the same checkout without it, then with it.
Example 3 · CheckoutService.java: without a service transaction, half the work stays
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/basics/CheckoutService.javapackage com.shoplite.lab.basics;
import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.placement.OrderLine;import com.shoplite.lab.placement.OutOfStockException;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class CheckoutService {
private final ProductRepository products;
public CheckoutService(ProductRepository products) { this.products = products; }
public void takeStockWithoutTransaction(List<OrderLine> lines) { takeStock(lines); }
@Transactional public void takeStockInOneTransaction(List<OrderLine> lines) { takeStock(lines); }
private void takeStock(List<OrderLine> lines) { for (OrderLine line : lines) { Product product = products.findById(line.productId()).orElseThrow(); if (product.getStock() < line.quantity()) { throw new OutOfStockException(product.getName(), product.getStock(), line.quantity()); } product.setStock(product.getStock() - line.quantity()); products.save(product); } }}
// src/main/java/com/shoplite/lab/basics/CheckoutDemo.javapackage com.shoplite.lab.basics;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;import com.shoplite.lab.placement.OrderLine;import com.shoplite.lab.placement.OutOfStockException;
@Component("checkout")public class CheckoutDemo implements LabDemo {
private final CheckoutService checkout; private final LabDb db; private final boolean oneTransaction;
public CheckoutDemo(CheckoutService checkout, LabDb db, @Value("${one-tx:false}") boolean oneTransaction) { this.checkout = checkout; this.db = db; this.oneTransaction = oneTransaction; }
@Override public void run() { List<OrderLine> cart = List.of(new OrderLine(9, 1), new OrderLine(3, 9)); try { if (oneTransaction) { checkout.takeStockInOneTransaction(cart); } else { checkout.takeStockWithoutTransaction(cart); } } catch (OutOfStockException e) { System.out.println("Checkout failed: " + e.getMessage()); } System.out.println("Clean Code stock in MySQL: " + db.stock(9)); }}$ java -jar target/tx-lab-0.1.0.jar --demo=checkout DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(724932458<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@6bdc984] DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(724932458<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1416278059<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@7bec83d5] DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(1416278059<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1289391419<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@73e054c0] DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(1289391419<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Checkout failed: Only 8 units of iPhone 15 128GB are in stock; 9 were requested. Clean Code stock in MySQL: 29 $ java -jar target/tx-lab-0.1.0.jar --demo=checkout --one-tx=true DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.basics.CheckoutService.takeStockInOneTransaction]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1677727024<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@3d45ea17] DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(1677727024<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(1677727024<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(1677727024<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback DEBUG o.s.orm.jpa.JpaTransactionManager : Rolling back JPA transaction on EntityManager [SessionImpl(1677727024<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Checkout failed: Only 8 units of iPhone 15 128GB are in stock; 9 were requested. Clean Code stock in MySQL: 30
What this code does
- First run, no
@Transactional:findByIdandsaveeach started and committed their own transaction, so the Clean Code unit was gone (29) even though the checkout failed on the iPhone. - Second run: one transaction named
takeStockInOneTransaction, every repository call participating, and a rollback at the end. Stock stayed at 30.
Where the annotation belongs:
- Service class or method: yes. Put it on the class for every public method, or on single methods.
- Controller: no. A transaction there holds a database connection while JSON is read and written, and a scheduled job or a test that calls the service gets none.
- Repository: already transactional per call; never rely on that for a multi-step operation.
Spring Data repositories have their own default transactions: SimpleJpaRepository is @Transactional(readOnly = true), and its write methods such as save and delete use a plain @Transactional. Inside a service transaction they join it. With no service transaction, each call is a separate transaction that commits on its own, so step one commits, step two fails and the database is left half-changed.
One business operation = one transaction: placing an order
Placing an order checks the customer and the address, takes stock for every item and saves the order with its items. The skeleton below does all of it in one @Transactional method.
Example 4 · OrderPlacementService.java: an order-placement skeleton in one transaction
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/placement/OrderPlacementService.javapackage com.shoplite.lab.placement;
import java.time.LocalDateTime;import java.time.temporal.ChronoUnit;import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Address;import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;import com.shoplite.order.Order;import com.shoplite.order.OrderItem;import com.shoplite.order.OrderRepository;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Placing an order is one business operation, so it is one transaction. */@Servicepublic class OrderPlacementService {
private final CustomerRepository customers; private final ProductRepository products; private final OrderRepository orders;
public OrderPlacementService(CustomerRepository customers, ProductRepository products, OrderRepository orders) { this.customers = customers; this.products = products; this.orders = orders; }
@Transactional public Order place(int customerId, int addressId, List<OrderLine> lines) { Customer customer = customers.findById(customerId) .orElseThrow(() -> new IllegalArgumentException("Customer " + customerId + " does not exist.")); Address address = customer.getAddresses().stream() .filter(a -> a.getId().equals(addressId)) .findFirst() .orElseThrow(() -> new IllegalArgumentException( "Address " + addressId + " does not belong to customer " + customerId + "."));
Order order = new Order(customer, address, LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)); for (OrderLine line : lines) { Product product = products.findById(line.productId()) .orElseThrow(() -> new IllegalArgumentException("Product " + line.productId() + " does not exist.")); if (product.getStock() < line.quantity()) { throw new OutOfStockException(product.getName(), product.getStock(), line.quantity()); } product.setStock(product.getStock() - line.quantity()); order.addItem(new OrderItem(product, line.quantity(), product.getPrice())); } return orders.save(order); }}
// src/main/java/com/shoplite/lab/placement/OutOfStockException.javapackage com.shoplite.lab.placement;
/** Unchecked, so Spring rolls the transaction back when it escapes a @Transactional method. */public class OutOfStockException extends RuntimeException {
public OutOfStockException(String productName, int available, int requested) { super("Only " + available + " units of " + productName + " are in stock; " + requested + " were requested."); }}
// src/main/java/com/shoplite/lab/placement/PlaceOrderDemo.javapackage com.shoplite.lab.placement;
import java.util.List;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;import com.shoplite.order.Order;
@Component("place-order")public class PlaceOrderDemo implements LabDemo {
private final OrderPlacementService placement; private final LabDb db;
public PlaceOrderDemo(OrderPlacementService placement, LabDb db) { this.placement = placement; this.db = db; }
@Override public void run() { System.out.println("--- Asha orders 1 x Clean Code and 2 x boAt Airdopes"); Order order = placement.place(1, 1, List.of(new OrderLine(9, 1), new OrderLine(6, 2))); System.out.println("Order " + order.getId() + " saved, total " + order.total());
System.out.println("--- Ravi orders 1 x Clean Code and 9 x iPhone 15 (only 8 left)"); try { placement.place(2, 3, List.of(new OrderLine(9, 1), new OrderLine(3, 9))); } catch (OutOfStockException e) { System.out.println("Failed: " + e.getMessage()); } System.out.println("Orders in MySQL: " + db.orders() + ", Clean Code stock: " + db.stock(9) + ", iPhone stock: " + db.stock(3)); }}$ java -jar target/tx-lab-0.1.0.jar --demo=place-order --logging.level.org.hibernate.SQL=DEBUG --- Asha orders 1 x Clean Code and 2 x boAt Airdopes DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.placement.OrderPlacementService.place]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(200027521<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@509cf379] DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(200027521<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? DEBUG org.hibernate.SQL : select a1_0.customer_id,a1_0.address_id,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.city,a1_0.state,a1_0.pincode from addresses a1_0 where a1_0.customer_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(200027521<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(200027521<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(200027521<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : insert into orders (customer_id,address_id,ordered_at,status) values (?,?,?,?) DEBUG org.hibernate.SQL : insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?) DEBUG org.hibernate.SQL : insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?) DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(200027521<open>)] DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Order 17 saved, total 3097.00 --- Ravi orders 1 x Clean Code and 9 x iPhone 15 (only 8 left) DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.placement.OrderPlacementService.place]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(26815371<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@16af0251] DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(26815371<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? DEBUG org.hibernate.SQL : select a1_0.customer_id,a1_0.address_id,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.city,a1_0.state,a1_0.pincode from addresses a1_0 where a1_0.customer_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(26815371<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(26815371<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback DEBUG o.s.orm.jpa.JpaTransactionManager : Rolling back JPA transaction on EntityManager [SessionImpl(26815371<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Failed: Only 8 units of iPhone 15 128GB are in stock; 9 were requested. Orders in MySQL: 17, Clean Code stock: 29, iPhone stock: 8
What this code does
- Asha's order: one transaction holds every SELECT, the order and item INSERTs and, at commit, the two stock UPDATEs from dirty checking.
- Ravi's order: Clean Code passed its check and its stock was changed in memory, then the iPhone check threw. The rollback discarded everything, so there are still 17 orders and 29 copies of Clean Code (one went to Asha).
OrderLineis a small record(int productId, int quantity). ShopLite's realOrderServiceadds the 422 checks and DTOs; this skeleton shows only the transaction.
Inside the method you work with managed entities. product.setStock(...) needs no save(), because dirty checking sends the UPDATE at commit, and orders.save(order) inserts the order while the cascade from the Relationships module inserts its items.
If any check throws, the proxy rolls back: stock already taken for earlier items is undone, and no order row exists.
Predict the output
Stock after a failed call
Clean Code starts with 30 copies. Predict its stock after each call.
Round 1 of 2
The service method is @Transactional.
JpaTransactionManager and the transaction log
JpaTransactionManager is the Spring bean that really begins, commits and rolls back JPA transactions. Spring Boot creates one when spring-boot-starter-data-jpa is on the classpath.
Turn on the transaction manager's DEBUG log while you learn or debug. Each log line then tells you what happened.
# Every transaction begin, commit and rollbacklogging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG# The SQL Hibernate sends, to see what happened inside itlogging.level.org.hibernate.SQL=DEBUGThe lines to look for:
Creating new transaction with name [Class.method]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT- a transaction begins;readOnlyappears at the end for read-only ones.Participating in existing transaction- an inner call (often a repository) joined the running one.Initiating transaction committhenCommitting JPA transaction- the method returned normally.Initiating transaction rollbackthenRolling back JPA transaction- the method threw an exception that rolls back.
Next step
Check your understanding
11 quick questions