Skip to content

Path 5 · lesson 1 of 5

Intermediate18 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.5.16 · Spring Framework 6.2

@Transactional that silently does nothing

A transaction starts in a proxy that stands in front of your bean. A private method, or a call from inside the same class, never reaches that proxy, and nothing tells you.

What you will learn

  • Explain where a transaction is started and committed when a method carries @Transactional
  • Predict whether a given call goes through the proxy or around it
  • Say why a private or final method cannot be made transactional in proxy mode
  • Prove in a running application whether a transaction is active inside a method
  • Choose between moving the method, self-injection and TransactionTemplate as the repair

Before you start

The concept

@Transactional is not an instruction to the method it sits on. It is a note for Spring. When the application starts, Spring finds beans that carry the note and wraps each one in a proxy: a second object that looks like your bean, opens a transaction, calls the real method, then commits or rolls back.

Other beans are given the proxy, not your object. So a transaction exists only when a call comes in through the proxy. Two kinds of call never do: a call to a method the proxy cannot intercept, and a call your object makes to itself.

Goes through the proxy

  • Another bean calls a public method on the injected reference.
  • A controller, a scheduler or a message listener calls the bean.
  • The transaction starts before your code and ends after it.

Goes around the proxy

  • A method calls another method of the same class: this.save() or just save().
  • The annotated method is private, so the proxy cannot override it.
  • The annotated method is final, for the same reason.
  • No error, no warning, no transaction.

Why it exists

The cost shows up on the day something throws halfway. An import saves 400 rows and fails on row 401. With a transaction, the table is unchanged. Without one, each save committed on its own, and 400 rows of a broken import are now live data that someone has to find and remove.

The second cost is less visible. Without a surrounding transaction, each repository call takes a connection from the pool and gives it back. A method that makes 20 calls borrows a connection 20 times, and reads made between the calls can see half of the work.

How it works inside

Spring Boot creates class-based proxies by default: at startup it generates a subclass of your bean with CGLIB and overrides its methods. The injected object is an instance of that subclass. The first two lines of the lab output show it.

Program outputjava -jar target/spring-production-lab-1.0.jar --demo=tx (Spring Boot 3.5.16, Java 21)

Real JVM output
Injected bean class: lab.TxService$SpringCGLIB$0
Is the injected object the TxService class itself? false

Is a transaction active inside the method?
  publicMethod():            transaction ACTIVE (lab.TxService.publicMethod)
  privateMethod():           NO transaction
  this.publicMethod():       NO transaction
The injected class is TxService$SpringCGLIB$0, a generated subclass, not TxService. Then three methods that all carry @Transactional report whether a transaction is active. Only the public method called from another bean has one. The private method and the public method called on this both run with no transaction.

A subclass can override a public, protected or package-visible method, so those can be intercepted. Since Spring Framework 6.0, protected and package-visible methods are transactional on class-based proxies. A subclass cannot override a private or a final method, so those run as plain Java whatever annotation they carry.

Self-invocation fails for a different reason. The proxy holds a reference to the real bean and delegates to it. Once the real method is running, this is the real bean. A call to another method on this is an ordinary Java call and never passes the proxy, even when the target method is public.

Program outputThe same run: two saves, an exception after the first

Real JVM output
Save two orders, throw after the first:
  via this (no proxy):  threw second order is invalid
  rows in purchase_order afterwards: 1   <- the first save was NOT rolled back
  via the proxy:        threw second order is invalid
  rows in purchase_order afterwards: 0   <- rolled back
The same method is called twice. Called on this from a method with no annotation, the first row stays in the table after the exception. Called through the proxy, the table is empty afterwards. The annotation and the code are identical in both cases; only the route of the call differs.
MethodCalled fromTransaction?
public, annotatedanother beanYes
protected or package-visible, annotatedanother bean in the same packageYes, on class-based proxies since Spring Framework 6.0
private, annotatedanywhereNo
final, annotatedanother beanNo
public, annotateda method of the same class that is not transactionalNo
public, annotateda method of the same class that is transactionalIt joins the caller's transaction; its own settings, such as REQUIRES_NEW, are ignored

Architecture

Drawing diagram…

A flowchart. The controller calls the proxy. The proxy asks the transaction manager to begin, calls the real service, then asks the transaction manager to commit or roll back. The real service has an arrow to itself labelled this.audit, which does not pass the proxy.

flowchart LR
    C["OrderController"] -->|"placeOrder()"| P["Proxy: generated subclass of TxService"]
    P -->|"begin transaction"| TM["Transaction manager"]
    P -->|"placeOrder()"| T["Real TxService"]
    T -->|"this.audit()"| T
    P -->|"commit or roll back"| TM
    TM --> DB[("Database connection")]
The controller holds the proxy. The call from the real bean to itself never touches it.
  • Everything transactional happens in the proxy: getting a connection, switching off auto-commit, committing, rolling back. Your class contains none of it.
  • The arrow from the real bean to itself is the whole problem. It is a plain method call inside one object, and there is nothing in its way to intercept.

Step by step

Drawing diagram…

A sequence diagram. The controller calls importOrders on the proxy, which starts no transaction and delegates to the real service. The service calls its own saveAll method directly. Row 1 is inserted and committed at once, row 2 fails, the exception returns to the controller and row 1 stays in the database.

sequenceDiagram
    participant C as Controller
    participant P as Proxy
    participant S as Real service
    participant DB as Database
    C->>P: importOrders()
    Note over P: importOrders has no annotation, so no transaction
    P->>S: importOrders()
    S->>S: this.saveAll()
    Note over S: saveAll is annotated, but the proxy is not involved
    S->>DB: insert row 1, committed at once
    S->>DB: insert row 2 fails
    S-->>C: exception
    Note over DB: row 1 stays
An annotated method called from an unannotated method of the same class.
  1. The proxy decides at the entry point, once. importOrders is not transactional, so the proxy passes the call straight on.
  2. From then on every statement runs on a connection in auto-commit mode, so each insert is its own small transaction and cannot be undone by a later failure.

In a real system

The usual way this reaches production is a refactor. A large public transactional method is split up, the annotation is moved onto one of the new private helpers because that is where the writes are, and the public method loses it. Every test still passes, because the tests check the happy path.

  • The same rule applies to every proxy-based annotation. @Async, @Cacheable, @Retryable and method security all work through the same proxy and all disappear on a self-call.
  • A checked exception does not roll back. By default Spring rolls back on RuntimeException and Error only. A method that throws a checked exception commits what it did unless you set rollbackFor.
  • Catching the exception hides the failure. If the method catches the exception and returns normally, the proxy sees a normal return and commits.

Java and Spring Boot

The service from the lab, labs/jvm/spring-production/src/main/java/lab/TxDemo.java, reduced to the three calls that the output above reports on.

src/main/java/lab/TxService.javaJava
@Serviceclass TxService {  static String tx() {    return TransactionSynchronizationManager.isActualTransactionActive()        ? "transaction ACTIVE" : "NO transaction";  }  @Transactional  public void publicMethod() { System.out.println(tx()); }       // ACTIVE  public void callsPrivate() { privateMethod(); }  @Transactional  private void privateMethod() { System.out.println(tx()); }     // NO transaction  public void callsPublicOnThis() { publicMethodCalledOnThis(); }  @Transactional  public void publicMethodCalledOnThis() { System.out.println(tx()); }  // NO transaction}

Why it is written this way

  • TransactionSynchronizationManager.isActualTransactionActive() is the direct way to ask whether the current thread has a real transaction. It is the quickest proof in a test or a debugger.
  • The second and third methods are reached through callsPrivate() and callsPublicOnThis(), which are public and go through the proxy. The proxy finds no annotation on them and starts nothing.

Wrong, then right

An import that must be all or nothing. The incorrect version puts the annotation where the writes are. The corrected version puts it on the method that other beans call.

Incorrect implementation

OrderImportService.java (incorrect)Java
@Serviceclass OrderImportService {  private final OrderRepository orders;  OrderImportService(OrderRepository orders) { this.orders = orders; }  public void importFile(List<OrderRow> rows) {    validate(rows);    saveAll(rows);            // a call on this: no proxy  }  @Transactional  private void saveAll(List<OrderRow> rows) {    for (OrderRow row : rows) orders.save(row.toOrder());  }}

Why it is written this way

  • The annotation is on a private method that is only called from inside the class. It has no effect twice over.

Why it fails

  • importFile is the method the proxy sees, and it is not transactional, so the proxy starts nothing and delegates.
  • saveAll is called on this. It runs as plain Java, and each orders.save commits on its own. A failure on a later row leaves the earlier rows in the table.

Corrected implementation

OrderImportService.java (corrected)Java
@Serviceclass OrderImportService {  private final OrderRepository orders;  OrderImportService(OrderRepository orders) { this.orders = orders; }  @Transactional  public void importFile(List<OrderRow> rows) {    validate(rows);    saveAll(rows);            // joins the transaction of importFile  }  private void saveAll(List<OrderRow> rows) {    for (OrderRow row : rows) orders.save(row.toOrder());  }}

Why it is written this way

  • The transaction boundary is the public entry point. Private helpers called from it run inside the same transaction without any annotation.

Trade-offs

  • The transaction now also covers validate. If validation is slow or calls another system, a database connection is held for all of that time.
  • When only part of a method should be transactional, or a part needs its own transaction, move that part to a separate bean or use TransactionTemplate, which needs no proxy at all.
  • Injecting the bean into itself also works and goes through the proxy, but it hides the reason for the call and is easy to remove by mistake.

Hands-on exercise

Find out which of your methods really have a transaction

Run the lab, read the three results, then change one line and predict the output before you run it again.

Steps · 0 of 4 done

What can go wrong

REQUIRES_NEW on a method called from the same class
Symptom
An audit record that should survive a rollback disappears together with the failed order.
Cause
The inner method was called on this, so its propagation setting was never read and it simply ran inside the outer transaction.
Fix
Move the audit write to its own bean, or run it with a TransactionTemplate configured with PROPAGATION_REQUIRES_NEW.
A checked exception that commits
Symptom
A method throws IOException halfway and the rows written before it are still there.
Cause
The default rollback rule covers unchecked exceptions and errors only.
Fix
Declare @Transactional(rollbackFor = Exception.class) where a checked exception must undo the work.
Testing the method directly
Symptom
A unit test builds the service with new and passes; production loses the rollback.
Cause
An object made with new has no proxy, so the test never exercised the transaction either way.
Fix
Write one integration test that makes the method fail halfway and asserts that the table is unchanged.

How to troubleshoot

Data stays after a failure that should have rolled it back

Check

TransactionSynchronizationManager.isActualTransactionActive() inside the method
How to read it
false means the call did not come through the proxy. Look at who calls the method: the same class, or a private or final method.
Not sure whether the bean is proxied at all

Check

bean.getClass().getName() on the injected reference
How to read it
A name containing $SpringCGLIB$ is a class-based proxy. The plain class name means nothing on the bean asked for a proxy.
No sign of transactions in the log

Check

logging.level.org.springframework.transaction.interceptor=TRACE
How to read it
The interceptor then logs "Getting transaction for" and "Completing transaction for" with the method name. A method that never appears never had a transaction.

Key takeaways

  • @Transactional works through a proxy placed in front of the bean. A transaction exists only for calls that enter through it.
  • A private or final method cannot be intercepted, and a call on this never reaches the proxy. Both fail without any message.
  • Put the annotation on the public method that other beans call. Private helpers called from it share its transaction.
  • To check, ask TransactionSynchronizationManager.isActualTransactionActive() or test that a failure leaves the table unchanged.

Practical check

Small scenarios, one decision each. Pick what you would do, then read why.

Scenario 1 of 2

A public method closeMonth() has no annotation. It loops over 300 accounts and calls this.closeAccount(account), which is public and annotated with @Transactional(propagation = REQUIRES_NEW). Account 120 throws.

What is in the database afterwards?

Scenario 2 of 2

A reviewer finds @Transactional on a private method applyDiscounts(). It is called from checkout(), a public method of the same class that carries @Transactional itself.

What should the review comment say?

References

References: Spring Framework reference: Using @Transactional (proxy mode, method visibility, self-invocation) ↗ · Spring Framework reference: Understanding AOP proxies (why a call on this is not intercepted) ↗ · Spring Framework reference: Rolling back a declarative transaction (default rollback rules) ↗ · Spring Framework reference: Programmatic transaction management (TransactionTemplate) ↗ · Report a problem