Video in progress

Strong Middle 🌱 Spring

A service method has no @Transactional and calls two repository methods. How does that work, and what is the risk?

Each repository call runs in its own transaction, through the @Transactional on SimpleJpaRepository. If the first one commits and the second fails, the data is left half-done; in addition, the returned entities are detached.

📖 Answer

@Service
class TransferService {
    public void transfer(long from, long to, BigDecimal sum) {
        Account a = accounts.findById(from).orElseThrow(); // transaction 1, closed
        Account b = accounts.findById(to).orElseThrow();   // transaction 2, closed
        a.withdraw(sum);
        b.deposit(sum);
        accounts.save(a);  // transaction 3: commit
        accounts.save(b);  // transaction 4: if this fails, the money is gone
    }
}

SimpleJpaRepository itself has @Transactional(readOnly = true) on the class, and @Transactional on its writing methods. With no outer transaction, each call opens and closes its own.

What breaks:

  • No atomicity: the money transfer above.
  • Dirty checking doesn't work. a and b are detached; if save() isn't called, the change is lost, and if it is, merge does an extra SELECT.
  • Lazy fields. a.getTransactions() gives LazyInitializationException (if open-in-view is off).
  • No isolation. Between the read and the write, another request may change the balance: a lost update.

The fix: put @Transactional on the service method and, if needed, read the accounts with a lock (@Lock(PESSIMISTIC_WRITE) or @Version).

How you detect it: with logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG, if the log shows "Creating new transaction" and "Committing" lines for each call, the boundary is placed wrongly.