Programmatic Transaction management in a SpringBoot application

Get a simple and practical understanding of Spring's programmatic transaction management.

Handling transactions is a very important matter when it comes to implementing business critical enterprise applications. SpringBoot applications have two methods of handling transactions namely declarative transaction management and programmatic way of handling. And here we will go through the way of using programmatic transaction management.

Say we need to handle transactions in a service class. And Say we have two separate operations that need to be transactional. Say those two methods are namelyinsertOrderRecords() and insertOrderMessages(). For a success Operation we need both of these to be completed without errors. And if in case there is an error occurring at insertOrderMessages() all the changes done at the insertOrderRecords() need to be roll-backed.

programmatic transaction management 1


So below listed are the steps to incorporate this scenario into transactions.

Get the PlatformTransactionManager injected into the service class ( place where we are going to perform the commit and rollback.) PlatformTransactionManager is automatically made available when we have a Spring boot application.

private PlatformTransactionManager txManager;

Get access to the TransactionStatus and perform the commit and rollback as below,

TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = txManager.getTransaction(def);
try {
} catch (Exception ex) {
throw ex;

Here there are two JDBC repositories working together to persist data. And underline methods must throw Exception in order to get them rollback. So in case of an exception everything will get rolled-back.