Video in progress
Why aren't the changes saved to the database in a `@Transactional` method called through `this.save()` inside a service?
@Transactional works through the Spring proxy. If the method is called from inside the same class through this, the proxy is bypassed and no transaction is opened. Without a persistence context there's no dirty checking either, so changing a loaded entity saves nothing.
📖 Answer
@Service
public class PriceService {
public void importAll(List<PriceRow> rows) { // no @Transactional
rows.forEach(this::apply); // a call that bypasses the proxy
}
@Transactional
public void apply(PriceRow row) {
Product p = repo.findBySku(row.sku()).orElseThrow(); // in its own short transaction
p.setPrice(row.price()); // we modified a detached object
}
}
When priceService.importAll() is called from outside, the proxy wraps only importAll, which has no annotation. The this.apply() inside is a plain Java call. repo.findBySku runs in the repository's own read-only transaction and finishes, so p is detached. The price changes, but nobody sends an UPDATE. There's no error.
The same situation applies to:
@Transactionalon aprivatemethod: the Spring proxy can't wrap it;- a
finalmethod or class (CGLIB can't override it).
Ways to fix it:
// 1) move the boundary to the outer method
@Transactional
public void importAll(List<PriceRow> rows) { rows.forEach(this::apply); }
// 2) if you need each row in its own transaction: TransactionTemplate
public void importAll(List<PriceRow> rows) {
rows.forEach(r -> tx.executeWithoutResult(s -> apply(r)));
}
Or move apply into a separate bean. Self-injection (@Lazy PriceService self) works too, but it muddies the code.
It's easy to check: log TransactionSynchronizationManager.isActualTransactionActive() inside the method, or watch the transaction open with logging.level.org.springframework.orm.jpa=DEBUG.
Sign up to mark studied questions and save your progress.