Spring / Spring7 basics Interview questions
What is the purpose of the @Transactional annotation?
@Transactional wraps a method (or every public method in a class) in a database transaction managed by Spring, automatically committing on success and rolling back on an unchecked exception, without you writing any manual begin/commit/rollback calls.
@Service public class TransferService { @Transactional public void transfer(Account from, Account to, BigDecimal amount) { from.debit(amount); to.credit(amount); } }
By default, it only rolls back on unchecked (RuntimeException) exceptions, not checked ones, unless you explicitly configure rollbackFor. Like AOP advice generally, @Transactional relies on proxying, so calling an annotated method from another method in the same class bypasses the proxy and the transaction never actually starts.
More Related questions...