Practice: transactions in Spring
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most transaction bugs come from four habits: throwing checked exceptions, catching what should fail the operation, calling a method the proxy never sees, and writing read-then-write code that loses updates. Each has a short fix.
Mistake 1: a checked exception that commits half the work
A @Transactional method that throws a checked exception commits what it did before the throw. A GST portal, a payment SDK or a file API is enough to cause it.
Example 1 · Mistake 1 fixed: rollbackFor on a checked GstPortalException
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/practice/InvoiceService.javapackage com.shoplite.lab.practice;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class InvoiceService {
private final ProductRepository products;
public InvoiceService(ProductRepository products) { this.products = products; }
/** As written by a teammate: the stock change survives a GST portal failure. */ @Transactional public void sellWithInvoice(int productId) throws GstPortalException { Product product = products.findById(productId).orElseThrow(); product.setStock(product.getStock() - 1); throw new GstPortalException("GST portal is down for maintenance"); }
/** Fixed: rollbackFor makes the checked exception roll back too. */ @Transactional(rollbackFor = GstPortalException.class) public void sellWithInvoiceFixed(int productId) throws GstPortalException { Product product = products.findById(productId).orElseThrow(); product.setStock(product.getStock() - 1); throw new GstPortalException("GST portal is down for maintenance"); }}$ java -jar target/tx-lab-0.1.0.jar --demo=practice-invoice Kurta stock: 35 Before the fix: GST portal is down for maintenance -> stock 34 After the fix: GST portal is down for maintenance -> stock 34
What this code does
- The first method committed although it threw: stock went from 35 to 34.
- The fixed method has
rollbackFor = GstPortalException.class, so its change was undone and the stock stayed at 34.
Translate the exception into a ShopLite runtime exception in the service, or add rollbackFor. Then the change is undone, and the global handler still answers the client.
Mistake 2: catching a failure that crossed a transactional proxy
If an inner @Transactional method joined the caller's transaction and threw, the transaction is already rollback-only. Catching the exception then ends in UnexpectedRollbackException.
Example 2 · Mistake 2 fixed: check instead of catching
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/practice/SafePurchaseService.javapackage com.shoplite.lab.practice;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class SafePurchaseService {
private final ProductRepository products; private final SafeLoyaltyService loyalty;
public SafePurchaseService(ProductRepository products, SafeLoyaltyService loyalty) { this.products = products; this.loyalty = loyalty; }
@Transactional public void buy(int customerId, int productId) { Product product = products.findById(productId).orElseThrow(); product.setStock(product.getStock() - 1); if (loyalty.canEarnPoints(customerId)) { loyalty.addPoints(customerId, 50); } else { System.out.println("No points: loyalty card of customer " + customerId + " is blocked"); } }}$ java -jar target/tx-lab-0.1.0.jar --demo=practice-safe-purchase No points: loyalty card of customer 2 is blocked Added 50 points for customer 1 Clean Code stock: 28
What this code does
- The blocked card is a normal case, so
canEarnPointsanswers it before any transactional call can fail. Nothing marks the transaction rollback-only. - Both sales committed (30 to 28); only the points for customer 2 were skipped.
Decide what the failure means. If it is a normal case (a blocked loyalty card), check it first and do not throw. If the side work must not affect the main work, give it its own REQUIRES_NEW transaction in another bean. Otherwise, let the operation fail.
Predict the output
What does the caller get?
The inner call fails and the outer method catches the exception.
Round 1 of 2
points.add is a @Transactional method of another bean and throws.
Mistake 3: a transaction the proxy never starts
Self-invocation, private and final methods, objects made with new and classes that are not beans all run without a transaction, silently. With JPA that means changes that are never saved.
Example 3 · Mistake 3 fixed: one transaction around the whole loop
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/practice/AllOrNothingPriceService.javapackage com.shoplite.lab.practice;
import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.TxProbe;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Fix 2: the outer method is the transaction, so the inner call needs no proxy of its own. */@Servicepublic class AllOrNothingPriceService {
private final ProductRepository products;
public AllOrNothingPriceService(ProductRepository products) { this.products = products; }
@Transactional public void applyFestivalPrice(List<Integer> productIds, BigDecimal newPrice) { for (int id : productIds) { updatePrice(id, newPrice); // plain call, already inside the transaction } }
private void updatePrice(int productId, BigDecimal newPrice) { TxProbe.print("updatePrice " + productId); Product product = products.findById(productId) .orElseThrow(() -> new IllegalArgumentException("Product " + productId + " does not exist")); product.setPrice(newPrice); }}$ java -jar target/tx-lab-0.1.0.jar --demo=practice-all-or-nothing [updatePrice 9] transaction active: true (com.shoplite.lab.practice.AllOrNothingPriceService.applyFestivalPrice) [updatePrice 10] transaction active: true (com.shoplite.lab.practice.AllOrNothingPriceService.applyFestivalPrice) Clean Code: 449.00, Pragmatic Programmer: 449.00 [updatePrice 11] transaction active: true (com.shoplite.lab.practice.AllOrNothingPriceService.applyFestivalPrice) [updatePrice 99] transaction active: true (com.shoplite.lab.practice.AllOrNothingPriceService.applyFestivalPrice) Failed: Product 99 does not exist Atomic Habits: 399.00, Cotton Kurta: 899.00
What this code does
- The private
updatePriceneeds no annotation: the probe shows it runs inside the outerapplyFestivalPricetransaction. - Product 99 failed in the second batch, so the change to product 11 rolled back with it: all or nothing.
A batch can end half applied for the same reason. First decide where the boundary belongs: around the whole loop (all or nothing), or per item (another bean or TransactionTemplate). Then check with the transaction log or TransactionSynchronizationManager.isActualTransactionActive().
Mistake 4: read, compute, write under concurrency
Reading a value into Java, changing it and writing it back is a lost update waiting to happen when two requests overlap.
Example 4 · Mistake 4 fixed: an atomic UPDATE for a hot counter
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/practice/BulkBuyService.javapackage com.shoplite.lab.practice;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.ProductRepository;
@Servicepublic class BulkBuyService {
private final ProductRepository products;
public BulkBuyService(ProductRepository products) { this.products = products; }
/** true when the units were taken; false when there were not enough left. */ @Transactional public boolean buy(int productId, int quantity) { return products.takeStock(productId, quantity) == 1; }}$ java -jar target/tx-lab-0.1.0.jar --demo=practice-bulk-buy 6 buyers want 2 each, 8 in stock: sold 4, refused 2, stock in MySQL: 0
What this code does
- Six buyers asked for 2 iPhones each at the same moment; exactly 4 got them and stock ended at 0, never below.
- No entity was read, so there was nothing to overwrite: the check and the change are one statement.
Transactions alone do not stop it. Use an atomic UPDATE for counters such as stock, @Version with a 409 for human edits, and PESSIMISTIC_WRITE in id order when the decision needs several rows. Keep every locking transaction short.
Order of execution
Two clerks with a pessimistic lock
Tap the steps in the order they happen.
Finish up
Mark complete & continue
Next: ShopLite: cancel an order safely