Sobes.tech
Senior

Features of using @Transactional in Spring. Transaction isolation levels.

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring is used for managing transactions at the method or class level. It allows automatically starting, committing, or rolling back a transaction during method execution.

Usage features:

  • By default, a transaction begins when entering the method and is committed upon successful completion.
  • If an unchecked exception (RuntimeException or Error) is thrown in the method, the transaction is rolled back.
  • Rollback behavior can be configured using the rollbackFor and noRollbackFor parameters.
  • Transactions only work when methods are called through Spring proxies; calling a method within the same class will not create a new transaction.

Transaction Isolation Levels determine how one transaction sees changes made by others:

  • READ_UNCOMMITTED — the lowest isolation level, allows reading uncommitted data (dirty read).
  • READ_COMMITTED — prevents dirty reads but allows non-repeatable reads and phantom reads.
  • REPEATABLE_READ — prevents dirty and non-repeatable reads, but phantom reads are possible.
  • SERIALIZABLE — the strictest isolation level, transactions are executed sequentially, preventing all types of anomalies.

Example usage:

@Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
public void updateData() {
    // business logic
}

Thus, @Transactional simplifies transaction management, and isolation levels allow balancing between performance and data consistency.