Self-invocation and other reasons @Transactional is ignored
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A price update runs without any error, the log shows nothing wrong, and the database still holds the old price. The annotation is on the method, yet no transaction ever started.
Self-invocation: this.method() bypasses the proxy
Self-invocation is a method calling another method of the same object, such as updatePrice(...) inside its own class. It means this.updatePrice(...) and skips the Spring proxy.
applyFestivalPrice loops over products and calls updatePrice, which carries @Transactional. Run it, then call updatePrice from outside and compare the prices.
Example 1 · FestivalPriceService.java: the self-invocation bug
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/pitfalls/FestivalPriceService.javapackage com.shoplite.lab.pitfalls;
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;
@Servicepublic class FestivalPriceService {
private final ProductRepository products;
public FestivalPriceService(ProductRepository products) { this.products = products; }
public void applyFestivalPrice(List<Integer> productIds, BigDecimal newPrice) { for (int id : productIds) { updatePrice(id, newPrice); } }
@Transactional public void updatePrice(int productId, BigDecimal newPrice) { TxProbe.print("updatePrice " + productId); Product product = products.findById(productId).orElseThrow(); product.setPrice(newPrice); }}
// src/main/java/com/shoplite/lab/pitfalls/SelfInvocationDemo.javapackage com.shoplite.lab.pitfalls;
import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("self-invocation")public class SelfInvocationDemo implements LabDemo {
private final FestivalPriceService prices; private final LabDb db;
public SelfInvocationDemo(FestivalPriceService prices, LabDb db) { this.prices = prices; this.db = db; }
@Override public void run() { System.out.println("1. Through applyFestivalPrice (calls this.updatePrice):"); prices.applyFestivalPrice(List.of(9, 10), new BigDecimal("449.00")); System.out.println(" Clean Code: " + db.price(9) + ", Pragmatic Programmer: " + db.price(10));
System.out.println("2. Calling updatePrice from outside, through the proxy:"); prices.updatePrice(9, new BigDecimal("449.00")); System.out.println(" Clean Code: " + db.price(9)); }}$ java -jar target/tx-lab-0.1.0.jar --demo=self-invocation 1. Through applyFestivalPrice (calls this.updatePrice): [updatePrice 9] transaction active: false 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(747992049<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@4936dca9] DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(747992049<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction [updatePrice 10] transaction active: false 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(2033906739<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@644a12be] DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(2033906739<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Clean Code: 499.00, Pragmatic Programmer: 650.00 2. Calling updatePrice from outside, through the proxy: DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.pitfalls.FestivalPriceService.updatePrice]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(499281381<open>)] for JPA transaction DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@68628510] [updatePrice 9] transaction active: true (com.shoplite.lab.pitfalls.FestivalPriceService.updatePrice) DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(499281381<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(499281381<open>)] DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction Clean Code: 449.00
What this code does
- Through
applyFestivalPrice,updatePriceprintedtransaction active: false, and the only transactions in the log are the repository's ownfindByIdones. The prices stayed 499.00 and 650.00. - Called from the demo bean, the same method went through the proxy:
Creating new transaction with name [...FestivalPriceService.updatePrice], and Clean Code became 449.00. TxProbeis the small helper in Example 4.
this is your real object, not the proxy, so the @Transactional on the called method is never seen. With no transaction running, findById runs in its own short repository transaction and returns an entity that is already detached. setPrice changes only the Java object, and no flush ever happens: quiet data loss.
The same method works the moment another bean calls it, because that call goes through the proxy. That is why this bug often passes a quick test and fails in the real flow.
Find the bug
Find the call with no transaction
The annotation is there, but the change is lost. Tap the wrong line.
applyAll calls updatePrice, which is @Transactional.
Round 1 of 2private and final methods, new, and classes that are not beans
A CGLIB proxy is a subclass that Spring generates at run time. It overrides your public methods to add the transaction around them.
The proxy can only wrap what it can override. The example calls four variants of the same method: public, private, an object made with new, and a final method.
Example 2 · StockFixService.java: public, private, new and final
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/pitfalls/StockFixService.javapackage com.shoplite.lab.pitfalls;
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;
@Servicepublic class StockFixService {
private final ProductRepository products;
public StockFixService(ProductRepository products) { this.products = products; }
@Transactional public void fixStock(int productId, int stock) { TxProbe.print("fixStock"); setStock(productId, stock); }
@Transactional public final void fixStockFinal(int productId, int stock) { TxProbe.print("fixStockFinal"); setStock(productId, stock); // runs on the proxy object, whose fields were never set }
public void fixStockPrivateCaller(int productId, int stock) { fixStockPrivate(productId, stock); }
@Transactional private void fixStockPrivate(int productId, int stock) { TxProbe.print("fixStockPrivate"); setStock(productId, stock); }
private void setStock(int productId, int stock) { Product product = products.findById(productId).orElseThrow(); product.setStock(stock); }}
// src/main/java/com/shoplite/lab/pitfalls/IgnoredAnnotationDemo.javapackage com.shoplite.lab.pitfalls;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;import com.shoplite.product.ProductRepository;
@Component("ignored")public class IgnoredAnnotationDemo implements LabDemo {
private final StockFixService stockFix; private final ProductRepository products; private final LabDb db;
public IgnoredAnnotationDemo(StockFixService stockFix, ProductRepository products, LabDb db) { this.stockFix = stockFix; this.products = products; this.db = db; }
@Override public void run() { System.out.println("1. public method on the Spring bean:"); stockFix.fixStock(8, 5); System.out.println(" stock of product 8: " + db.stock(8));
System.out.println("2. private @Transactional method:"); stockFix.fixStockPrivateCaller(8, 6); System.out.println(" stock of product 8: " + db.stock(8));
System.out.println("3. object made with new (not a Spring bean):"); StockFixService manual = new StockFixService(products); manual.fixStock(8, 7); System.out.println(" stock of product 8: " + db.stock(8));
System.out.println("4. final @Transactional method:"); try { stockFix.fixStockFinal(8, 8); } catch (NullPointerException e) { System.out.println(" NullPointerException: " + e.getMessage()); } System.out.println(" stock of product 8: " + db.stock(8)); }}$ java -jar target/tx-lab-0.1.0.jar --demo=ignored 1. public method on the Spring bean: [fixStock] transaction active: true (com.shoplite.lab.pitfalls.StockFixService.fixStock) stock of product 8: 5 2. private @Transactional method: [fixStockPrivate] transaction active: false stock of product 8: 5 3. object made with new (not a Spring bean): [fixStock] transaction active: false stock of product 8: 5 4. final @Transactional method: [fixStockFinal] transaction active: false NullPointerException: Cannot invoke "com.shoplite.product.ProductRepository.findById(Object)" because "this.products" is null stock of product 8: 5
What this code does
- Only case 1 had a transaction, so only it changed the stock (0 to 5). The private method and the object made with
newsilently ran without one, and their changes to 6 and 7 were lost. - The final method ran on the proxy instance itself: its
productsfield was never set, hence theNullPointerException. Spring printed no warning at startup in this run.
Anything the proxy cannot override, or never wrapped, gets no transaction:
privatemethod: a subclass cannot override it, so@Transactionalon it is ignored (calls to it are self-invocations anyway).finalmethod: also not overridable. Worse, it runs on the proxy object itself, whose fields Spring never set, so injected fields arenull.- An object made with
new MyService(...): Spring never saw it, so there is no proxy at all. - A class that is not a bean (no
@Service, not picked up by component scanning): same asnew.
Predict the output
Does it get a transaction?
Each method is annotated with @Transactional.
Round 1 of 3
Does restock run in a transaction?
Fixes: another bean, a better structure, or TransactionTemplate
TransactionTemplate starts and ends a transaction in code: tx.executeWithoutResult(status -> ...). No proxy is involved.
Two fixes follow: PriceWriter as a second bean, and a TransactionTemplate that opens one transaction per product in code.
Example 3 · PriceWriter.java and TransactionTemplate: two fixes
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/pitfalls/PriceWriter.javapackage com.shoplite.lab.pitfalls;
import java.math.BigDecimal;
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 1: the transactional method lives in its own bean, so callers always go through a proxy. */@Servicepublic class PriceWriter {
private final ProductRepository products;
public PriceWriter(ProductRepository products) { this.products = products; }
@Transactional public void updatePrice(int productId, BigDecimal newPrice) { TxProbe.print("PriceWriter.updatePrice " + productId); Product product = products.findById(productId) .orElseThrow(() -> new IllegalArgumentException("Product " + productId + " does not exist")); product.setPrice(newPrice); }}
// src/main/java/com/shoplite/lab/pitfalls/FestivalPriceJob.javapackage com.shoplite.lab.pitfalls;
import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Service;
/** Calls the other bean once per product: one transaction per product, through the proxy. */@Servicepublic class FestivalPriceJob {
private final PriceWriter writer;
public FestivalPriceJob(PriceWriter writer) { this.writer = writer; }
public void apply(List<Integer> productIds, BigDecimal newPrice) { for (int id : productIds) { writer.updatePrice(id, newPrice); } }}
// src/main/java/com/shoplite/lab/pitfalls/FestivalPriceTemplateJob.javapackage com.shoplite.lab.pitfalls;
import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.support.TransactionTemplate;
import com.shoplite.lab.TxProbe;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Fix 3: start each transaction in code with TransactionTemplate. No proxy is involved. */@Servicepublic class FestivalPriceTemplateJob {
private final ProductRepository products; private final TransactionTemplate tx;
public FestivalPriceTemplateJob(ProductRepository products, TransactionTemplate tx) { this.products = products; this.tx = tx; }
public int apply(List<Integer> productIds, BigDecimal newPrice) { int updated = 0; for (int id : productIds) { try { tx.executeWithoutResult(status -> { TxProbe.print("template, product " + id); Product product = products.findById(id) .orElseThrow(() -> new IllegalArgumentException("Product " + id + " does not exist")); product.setPrice(newPrice); }); updated++; } catch (IllegalArgumentException e) { System.out.println(" skipped: " + e.getMessage()); } } return updated; }}
package com.shoplite.lab.pitfalls;
import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("fixes")public class FixesDemo implements LabDemo {
private final FestivalPriceJob job; private final FestivalPriceTemplateJob templateJob; private final LabDb db;
public FixesDemo(FestivalPriceJob job, FestivalPriceTemplateJob templateJob, LabDb db) { this.job = job; this.templateJob = templateJob; this.db = db; }
@Override public void run() { System.out.println("Fix 1: a separate PriceWriter bean"); job.apply(List.of(9, 10), new BigDecimal("449.00")); System.out.println(" Clean Code: " + db.price(9) + ", Pragmatic Programmer: " + db.price(10));
System.out.println("Fix 3: TransactionTemplate, one transaction per product"); int updated = templateJob.apply(List.of(11, 99, 12), new BigDecimal("349.00")); System.out.println(" updated " + updated + ": Atomic Habits " + db.price(11) + ", Cotton Kurta " + db.price(12)); }}$ java -jar target/tx-lab-0.1.0.jar --demo=fixes Fix 1: a separate PriceWriter bean [PriceWriter.updatePrice 9] transaction active: true (com.shoplite.lab.pitfalls.PriceWriter.updatePrice) [PriceWriter.updatePrice 10] transaction active: true (com.shoplite.lab.pitfalls.PriceWriter.updatePrice) Clean Code: 449.00, Pragmatic Programmer: 449.00 Fix 3: TransactionTemplate, one transaction per product [template, product 11] transaction active: true [template, product 99] transaction active: true skipped: Product 99 does not exist [template, product 12] transaction active: true updated 2: Atomic Habits 349.00, Cotton Kurta 349.00
What this code does
- Fix 1: the job calls
PriceWriterthrough its proxy, so every product gets its own transaction namedPriceWriter.updatePrice, and both prices became 449.00. - Fix 3:
TransactionTemplatestarts one transaction per product in code (it has no method name, so the probe shows none). Product 99 failed and only its transaction rolled back; the other two were saved.
The best fix is usually a second bean: move the transactional method to its own class and inject it, so every call crosses a proxy and the classes come out cleaner. If the whole loop must be all or nothing, put @Transactional on the outer method instead; the inner calls then run inside it and need no annotation.
Use TransactionTemplate when you need a transaction per item, or when the boundary depends on data. Spring Boot auto-configures one. Avoid injecting a bean into itself to reach its own proxy: it works, but hides the design problem.
Checking at runtime with TransactionSynchronizationManager
TransactionSynchronizationManager.isActualTransactionActive() returns true when the current thread runs inside a real transaction.
TxProbe is a one-line check to use while debugging or in a test. The example calls it on the request thread and on a new thread.
Example 4 · TxProbe.java: is there a transaction on this thread?
Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/TxProbe.javapackage com.shoplite.lab;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/** Prints whether the current thread runs inside a real transaction, and its name. */public final class TxProbe {
private TxProbe() { }
public static void print(String where) { boolean active = TransactionSynchronizationManager.isActualTransactionActive(); String name = TransactionSynchronizationManager.getCurrentTransactionName(); System.out.println(" [" + where + "] transaction active: " + active + (name != null ? " (" + name + ")" : "")); }}
// src/main/java/com/shoplite/lab/practice/BackgroundThreadService.javapackage com.shoplite.lab.practice;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.TxProbe;
@Servicepublic class BackgroundThreadService {
@Transactional public void placeAndNotify() throws InterruptedException { TxProbe.print("request thread"); Thread sms = new Thread(() -> TxProbe.print("new thread")); // a transaction belongs to one thread sms.start(); sms.join(); }}$ java -jar target/tx-lab-0.1.0.jar --demo=practice-thread [request thread] transaction active: true (com.shoplite.lab.practice.BackgroundThreadService.placeAndNotify) [new thread] transaction active: false
What this code does
isActualTransactionActive()is true on the request thread and names the transaction after the method that started it.- The new thread started inside the same method has no transaction: Spring binds the transaction and its
EntityManagerto one thread, so database work in another thread must start its own.
getCurrentTransactionName() gives the transaction's name, usually Class.method of the method that started it, and isCurrentTransactionReadOnly() reports read-only ones. The DEBUG log is the other check: a missing Creating new transaction with name [...] line for your method means it had no transaction.
Transactions are bound to the thread. Work handed to a new thread or an executor runs without the caller's transaction.
Next step
Check your understanding
11 quick questions