Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-17 12:10:14 Viewed : 69
Here are code examples demonstrating both declarative and programmatic transaction management in Spring Boot:
@Transactional
:java@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
public void updateProduct(Product product) {
// Perform business logic and update product
productRepository.save(product);
}
}
In this example, the updateProduct
method is annotated with @Transactional
. This declarative approach ensures that the method runs within a transaction. If an exception occurs during the method execution, the transaction will be automatically rolled back, and any changes made to the ProductRepository
will be undone.
TransactionTemplate
:java@Service
public class ProductService {
@Autowired
private PlatformTransactionManager transactionManager;
@Autowired
private ProductRepository productRepository;
public void updateProduct(Product product) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(status -> {
try {
// Perform business logic and update product
productRepository.save(product);
return null;
} catch (Exception e) {
status.setRollbackOnly();
throw e;
}
});
}
}
In this example, the updateProduct
method manually manages the transaction using the TransactionTemplate
from the PlatformTransactionManager
. The execute
method takes a TransactionCallback
functional interface, where you define the transactional logic. If an exception occurs during the execution, status.setRollbackOnly()
is called to mark the transaction for rollback.
Please note that you need to configure the PlatformTransactionManager
bean appropriately in your Spring Boot application context for programmatic transaction management to work correctly.
These examples demonstrate the difference between declarative and programmatic transaction management approaches in Spring Boot. Declarative transaction management simplifies the code by using annotations, while programmatic transaction management provides more fine-grained control by manually managing transactions using transaction templates or APIs.