Example using @Transactional

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-17 11:26:19 Viewed : 73

In Spring Boot, the TransactionTemplate is not commonly used. Instead, the @Transactional annotation is typically utilized for transaction management. Let me provide an updated example using @Transactional.

@Service public class ExampleService { @Autowired private TransactionalService transactionalService; @Transactional public void performTwoTransactions() { try { // Perform transaction 1 transactionalService.transaction1(); // Perform transaction 2 transactionalService.transaction2(); } catch (Exception e) { // Handle exceptions or rethrow } } }

In this example, the ExampleService class calls two transactional methods transaction1() and transaction2() from a separate TransactionalService class. Both methods are annotated with @Transactional. If an exception occurs in either method, the transactional aspect of Spring will automatically roll back both transactions.

@Service public class TransactionalService { @Autowired private UserRepository userRepository; @Transactional public void transaction1() { // Perform operations with userRepository } @Transactional public void transaction2() { // Perform operations with userRepository } }

In the TransactionalService, the transaction1() and transaction2() methods are annotated with @Transactional. This annotation ensures that each method runs within its transactional context. If an exception occurs, Spring will handle the transaction rollback.

By utilizing the @Transactional annotation, you can simplify transaction management in Spring Boot and achieve the desired rollback behavior within a method.

Related Articles

Leave a Comment: