Data Transaction with Spring — part 2

Dilanka Muthukumarana
5 min readJan 10, 2019

This is the part 2 of Data Transaction with Spring, previously I have added an overview of the transactions with Spring with part 1. If you haven’t read yet, you can find it on below link.

With this article, I would like to discuss the below content as promised in end of part 1.

  1. Entity Manager vs Database Transactions
  2. Implementing Programmatic Transaction Management
  3. Implementing Declarative Transaction Management

Entity Manager vs Database Transactions

An instance of the interface EntityManager is used to initiate a persistence-context. We can obtain EntityManager instance by calling EntityManagerFactory#createEntityManagerFactory.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistantUnit");
EntityManager entityManager = emf.createEntityManager();

What is persistence-context?

An EntityManager instance is associated with a persistence-context. The persistence-context is a set of managed unique entity instances. EntityManger interacts with this context to manage entity instances and their lifecycle.

EntityManager is not thread-safe, so we should use only one instance per thread.

Each EntityManagerFactory instance provides EntityManager instances that are all configured in the same manner, i.e. all will be using the same persistence-unit. More than one EntityManagerFactory instances can be used per application which would probably be pointing to a different set of entities and data-sources etc.

When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory by calling emf.close(). Once an entity manager factory has been closed, all entity managers created from it are considered to be in the closed state as well.

Life Cycle and Scope

There are two separate concepts to consider.

  1. Database transactions
  2. Persistence Context

each of them has separate own life cycle and scope. When using @Transactional annotation, it is only defined single transaction in the scope of the persistence context. Means Database transaction happens in the scope if persistence context.

Persistence Context is coming from the JPA as it is implemented hibernate session internally. So it used to handle a set of entities that contain data to be persisted.

Implementing Declarative Transaction Management

When considering Declarative Transaction Management, there are few things that most important to talk, such as,

  1. Annotations such as @EnableTransactionManagement and @Transactional.
  2. Aspect Oriented Programming (AOP)
  3. Rollback Transaction

@EnableTransactionManagement and @Transactional — Allowed us to add transaction management to code without any trouble.

Aspect Oriented Programming — This is a programming concept that helps to break a programming logic into unique parts. Spring using this concept when doing transaction management.

Transaction management in Spring is base on proxies. Let’s see what is the behavior without proxies and with proxies.

Without proxy — When you invoke a method of an object reference from the calling program. It will directly invoke on that object reference.

With Proxywhen you invoke a method of an object reference from the calling program, a method is no longer invoke an actual object reference. But instead of that call will invoke in a proxy object and a proxy object will delegate to the actual object reference with all other operations which meant to do by the Spring itself.

Briefly, Proxy is a transaction interceptor which intercepts method calls and manages all the life cycle events of the associated target object. This helps to Platform Transaction Manager to handle the transaction effectively. So @Transactional annotation is a proxy which defaults advice mode for processing transactions.

So there are four proxy components:

  1. Persistent context proxy — Database transaction and set of managed entity instances exist in the database as well as defines the scope of an entity instance. (created, persisted, removed)
  2. Entity Manager proxy — Manages entities lives a database and define methods used in the persistent context.
  3. Transaction Aspect — manages transactions with this any method which declared @Transactional annotation. intercepts the method calls of an associated target class or object. As well as responsible for transactional state management such as begin, commit, rollback or suspend.
  4. Transaction Manager — responsible for Spring’s Platform Transaction Manager which implements JPA Transaction Manager.

In Declarative Transaction Management uses the @Transactional annotation. This annotation can be used either class or method level.

if the annotation using a class or interface level, All methods within it become transactional. If using in method level, it will override class level annotations.

The recommended way is to annotate the concrete classes and interfaces.

Configuration

There are two ways to configure transaction in Spring.

  1. XML-based — Uses the XML files located outside of the code to configure.
  2. Annotation-based — Used Java annotations in the code level.

Transaction Advice (Parameters)

The @Transactional annotation has several parameters which called as transaction advice. Let’s have a look into it little bit.

@Transactional(isolation=…..) — All propagation types have introduced in part 1.

@Transactional(propagation=…) — There are few propagation levels of a transaction.

@Transactional(propagation=Propagation.REQUIRED)  //code will always run in a transaction@Transactional(propagation=Propagation.REQUIRES_NEW) // code will always run in new transaction even if the calling method has not transaction initiated@Transactional(propagation=Propagation.NEVER) // indicated that method should not run in transaction. 

@Transactional(timeout=…) — Represents that time limit of the for the operation in the method.

@Transactional(timeout=50)

@Transactional(readOnly=…) — Indicate that transaction do not need to write to the database, defaults value is false. This will help to optimize the data access as well as provide some hint/indication to the persistent provide to not to initiate or monitor any write attempts failures.

@Transactional(readOnly=true)

@Transactional(rollbackFor=…) — by default rollback happens the only runtime unchecked exceptions only. For the checked exceptions does not trigger the rollback transactions. Using this option developer has flexibility to manage rollback for the given exception or multiple exceptions.

@Transactional(rollbackFor=Exception.class)

@Transactional(rollbackForClassName={“Exception”}) — this defines more flexibility to developer. The developer can rollback the transaction with the class name of the exception.

@Transactional(rollbackForClassName={“NullPointerException”})

@Transactional(noRollBackFor=…) — This defines far more flexibility to the developer if rollback happens in a way on unwanted behavior or error as well as developer needed to skip the rollback operation this is the advice need to use.

@Transactional(noRollBackFor=NoSuchElementException.class)

Implementing Programmatic Transaction Management

Spring provides two types of programmatic transaction management.

  1. Transaction Template — This is similar to Spring templates like JDBC template and other available templates.
  2. Platform Transaction Manager — Handles transactions across Hibernate, JPA, JDBC, JMS, etc..

Transaction Template

Transaction template simplifies the programmatic transaction execution by wrapping the transaction manager API and provide a template method where the transactional boundaries. After the rollback method completed, the transaction is committed.

Using the transaction template, the developer can configure the transaction related settings such as propagation mode, isolation level, timeout, etc..

public void doInTransaction(PlatformTransactionManager transacionManager){   this.transactionTemplate = new       TransacionTemplate(transacionManager); this.transactionTemplate.setPropagationBehaviorName("PROPAGATION_REQUIRES_NEW");  this.transactionTemplate.setTimeOut(true);}

I hope this article gave you some sort of understanding about the transaction handling with Spring Framework.

Thank you. Cheers!

--

--

Dilanka Muthukumarana

TOGAF® Enterprise Architecture Practitioner | Experienced Software Professional | Freelance Architect/Consultant https://buy.stripe.com/8wMbMpdvO31ycsUbII