@Transactional — Spring Technical Interview Questions & Answers

Declarative transaction boundaries around service methods.

@Transactional

  • @Transactional runs a method inside a database transaction.
  • If something fails with a runtime error, changes can roll back together.
  • Put it on service methods that change multiple rows as one unit.
  • readOnly = true is useful for query-only methods.
  • propagation settings control nested transaction behaviour (REQUIRED is default idea).
  • Catching exceptions inside the method so rollback never triggers.
  • All-or-nothing for multi-step DB updates.

Technical Interview Tip: Explain rollback with a money-transfer style example.

Code Examples for @Transactional

@Transactional — working example

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
class TransferService {
  private final AccountRepository accounts;

  TransferService(AccountRepository accounts) {
    this.accounts = accounts;
  }

  @Transactional
  public void transfer(long fromId, long toId, long amount) {
    Account from = accounts.findById(fromId).orElseThrow();
    Account to = accounts.findById(toId).orElseThrow();
    from.debit(amount);
    to.credit(amount);
  }
}

@Transactional wraps a method in a DB transaction — rollback on runtime failures by default.

How to Explain @Transactional to an Interviewer

What is @Transactional (sb db transactions)?

Used for a short @Transactional sb db transactions example a small REST app Not just the heading

Give one small example of @Transactional (sb db transactions).

the smallest @Transactional sb db transactions example you can type Declarative transaction boundaries around service methods

What mistake do beginners make with @Transactional (sb db transactions)?

only saying “@Transactional sb db transactions” with no example Show the fix

Where do you use @Transactional (sb db transactions)?

a small REST app a short @Transactional sb db transactions example