Sobes.tech
Middle

What is the @Transactional annotation in Java?

sobes.tech AI

Answer from AI

The @Transactional annotation in Java is used for declarative transaction management. It allows defining transaction boundaries, specifying which methods should be executed within a single transaction.

Main aspects:

  • Integration: Most often used in conjunction with Spring Framework, EJB, or other frameworks that provide transaction management.
  • Proxying: The framework creates a proxy object that wraps the target object with annotated methods. Before calling an annotated method, the proxy starts a transaction, and after its execution, it commits or rolls it back depending on the outcome (whether an exception was thrown).
  • Attributes: Has various attributes to configure transaction behavior, such as:
    • propagation: defines how a transactional method should behave when called from another transactional context. For example, REQUIRED, REQUIRES_NEW, SUPPORTS, NOT_SUPPORTED, NEVER, MANDATORY.
    • isolation: defines the isolation level for the transaction. For example, READ_COMMITTED, READ_UNCOMMITTED, REPEATABLE_READ, SERIALIZABLE.
    • readOnly: indicates that the transaction is read-only, which can sometimes optimize performance.
    • timeout: sets the wait time for the transaction.
    • rollbackFor and noRollbackFor: specify which exceptions should cause the transaction to rollback or not.

Usage example:

// Example of usage in Spring
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    // This method will be executed within a transaction
    @Transactional
    public void createUser() {
        // Logic for creating a user and saving to the database
        // If a RuntimeException is thrown, Spring will rollback the transaction
    }

    // This method will be executed within a transaction with specific settings
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public User findUserById(Long id) {
        // Logic for finding a user
        return null; // Example
    }
}

@Transactional simplifies transaction management, allowing developers to focus on business logic rather than low-level transaction API management (e.g., JTA or JDBC Connection).