Usage of @Transactional annotation.

@Transactional is a Spring annotation used to manage database transactions automatically. It ensures that a group of database operations executes as a single unit of work. If all operations complete successfully, the transaction is committed; if any operation fails, the entire transaction is rolled back, maintaining data consistency and integrity.

Key Points: • Ensures all database operations within a transaction either succeed together or fail together. • Eliminates manual transaction management code by allowing Spring to handle commit and rollback operations. • Supports transaction features such as propagation, isolation levels, timeout, and rollback rules.

Example: Consider a banking application where money is transferred from one account to another. Both the debit and credit operations must succeed together. If one operation fails, the transaction should roll back to prevent inconsistent account balances.

Code Example:

@Service
public class BankService {

    @Transactional
    public void transferMoney(

Long fromAccount, Long toAccount,

            double amount) {

        debitAccount(
                fromAccount,
                amount);

        creditAccount(
                toAccount,
                amount);
    }
}

In this example: • If both operations succeed, the transaction is committed. • If any exception occurs, all changes are rolled back.

Common Usage: • Money transfers. • Order processing. • Inventory updates. • User registration involving multiple database tables. • Batch processing operations.

Important Attributes:

• propagation - Defines how transactions interact with existing transactions.

• isolation - Controls data visibility between concurrent transactions.

• rollbackFor - Specifies exceptions that should trigger rollback.

• timeout - Defines the maximum transaction duration.

• readOnly - Optimizes read-only database operations.

Best Practices: • Apply @Transactional at the service layer. • Keep transactions short to improve performance. • Avoid placing transactional logic in controllers. • Use readOnly = true for query-only methods.

Interview Tip: A concise interview answer is: @Transactional is used to define a transactional boundary in Spring. It ensures that multiple database operations execute as a single unit of work, where all changes are committed if successful or rolled back if an error occurs, thereby maintaining data consistency and integrity.