Programmatic Transaction management in a SpringBoot application

  • November 14, 2018
  • 0
99xtechnology

Mano Dasanayaka

Senior Tech Lead

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 namely insertOrderRecords() 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.

 

insertOrderRecords();

insertOrderMessages();

 

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.

 

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

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.

Add comment

Your email address will not be published. Required fields are marked *