Sobes.tech
Junior — Middle

How can multiple operations be ensured to execute within a single transaction in code?

sobes.tech AI

Answer from AI

In Java, to ensure the execution of multiple operations within a single transaction, mechanisms provided by frameworks, such as the Spring Framework, are usually used.

Main methods:

  1. @Transactional annotation — allows marking a method, within which all operations will be executed in a single transaction. If an exception occurs during execution, the transaction is rolled back.
@Service
public class MyService {

    @Transactional
    public void performOperations() {
        // operation 1
        // operation 2
        // both operations will be in one transaction
    }
}
  1. Programmatic transaction management via PlatformTransactionManager — a lower-level method where the transaction is started and ended manually.
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
    // operations
    transactionManager.commit(status);
} catch (Exception e) {
    transactionManager.rollback(status);
}

Thus, all operations within a transaction either succeed together or are rolled back in case of an error, ensuring data integrity.