Wednesday, August 25, 2021

Spring @Transactional Annotation Example - How to Manage Transaction using Spring Framework?

One of the most essential parts of Spring MVC is the @Transactional annotation, which provides broad support for transaction management and allows developers to concentrate on business logic rather than worrying about data integrity in the event of system failures. Spring Framework provides declarative and programmatic transaction management, and developers can choose between convenience and control, depending on the requirement. Declarative transaction management is easier and suitable in most cases, but in some cases, you want fine-grain control, and you can use the declarative transaction. We'll see examples of both declarative and programmatic transaction management in this article. 

Some of the main benefits that can be obtained through transaction management are,

1. TransactionTemplate or PlatformTransactionManager implementations are used to support programmatic transaction management.

2. You can use JDBC, Hibernate, Spring Data JPA, JDO, JTA, and others.

3. Can be used in declarative transaction management. Spring uses AOP (Aspect Orient Programming) over the transactional methods to provide data integrity.

So in this tutorial, let’s first discuss database transactions, and then we'll see how the spring framework can manage transactions in Java applications. A database transaction is a sequence of actions that are treated as a single unit of work. The concepts of transactions can be described with the following four key properties called ACID properties.

1. Atomocity – This refers to either the entire sequence of operation is successful or unsuccessful.

2. Consistency – Consistency of referential integrity of the database.

3. Isolation – There may be many transactions processing with the same data set simultaneously.

4. Durability – Results of the transactions can not be erased from the database due to system failures.

Read-write and read-only transaction routing in Spring

A real RDBMS database system will guarantee all four properties for each transaction. Spring framework is also used to provide an abstract layer on top of the different underlying transaction management APIs. 

Basically, there are two distinct ways to configure Transactions, annotations, and AOP, each with its own advantages. We're going to discuss the more common annotation-config here.

public class PersistenceJPAConfig{

public PlatformTransactionManager transactionManager(){
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    entityManagerFactoryBean().getObject() );
    return transactionManager;

But if you use the Spring boot project with this dependency spring-boot-starter-data-jpa, then transaction management will be enabled by default.

Spring @Transactional Example - How to Manage Transaction using Spring Framework? 

2. The @Transactional Annotation

You can annotate a bean with @Transactional either at the class or method level.

import org.springframework.stereotype.Service;
import javax.transaction.Transactional;

public class ProductService {


From the above code, you can see that @Transactional annotation enables,

1. Rollback rules of the transactions

2. Transaction should be read-only

3. Isolation level of the transaction

4. Timeout of the operation wrapped by transaction

Note: The checked exception does not trigger a rollback of the transaction. This is one of the important things to know and remember as it can cause issues. You can further read comprehensive spring books or join comprehensive courses to learn more about transaction management in the spring framework. 


3. Transaction Management in Spring Framework

When it comes to transaction management, there are two 2 ways to achieve it. Spring Programmatic transaction management and Spring Declarative transaction management. Will have a quick introduction to both these methods.

3.1  Spring Programmatic Transaction Management.

Transaction management code needs to be explicitly written, and it is tightly bound to business logic in this case. This allows you to manage the transaction with the help of programming in your source code. That gives you extreme flexibility, but it is difficult to maintain.

StudentTransaction studentTransaction = entityManager.getTransaction();
try {
    studentTransaction.begin(); //start of the first student transaction
   //this is the place that used to create students and link them
  /* register student - query 1
      create student
     link note to the user - query 2 */

    //Commit Student Transaction
    } catch(Exception exception) {
          //Rollback Student Transaction
        throw exception;

3.2 Spring Declarative Transaction Management

Instead of hard coding in your source code, you can handle the transaction with the help of settings. To manage transactions, you only need to utilize annotations or XML-based settings. This also allows the transaction management and business code to be separated. Some of the steps associated with the declarative transaction are,

1. If the method has been included in the transactional configuration, then the created advice will begin the transaction before calling the method

2. Target method will be executed in a try/catch block.

3. If the method finishes normally, the AOP advice commits the transaction successfully; otherwise, it performs a rollback.

public void addStudentToSpecificClass() {
/* register student - query
create new student
link student to class - query 2 */

Different types of Transaction Propagation in Transaction Management specify whether or not the related component will participate in the transaction and what occurs if the caller component/service has or has not previously created/started a transaction.

That's all about how to use @Transactional annotation in Java with Spring Framework. The basic setting of transactional semantics using Java was addressed in this article. We also learned how to use @Transactional and what a Transactional Strategy should look like.

Other Spring Framework articles you may like to explore 

Thanks for reading this article so far. If you like these Spring @Transaction tutorials and examples then, please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are new to Spring and Spring MVC and looking for free online courses to kickstart your learning then I highly recommend you to check these free Spring MVC courses. It also includes free core spring and spring boot courses from Udemy and Coursera. 

No comments :

Post a Comment