0
votes

I am very new to transactions in spring.Due to some code standards used by my organization , i asked to join parent transaction if exist while calling any method.

My application is a Spring MVC application having three layers

  1. Web Layer(controller classes)
  2. Service Layer(Service class containing business logic)
  3. DAO Layer (DAO(Data access layer) classes for DB related query )

Now in a method on service layer uses three different methods of dao layer. I have annotated this service method as transactional in nature by using @Transactional. Now i want all three dao methods called from this service layer methods also be transactional in nature and must join the parent transaction started by service layer method insisted of starting other new translations for each dao methods.

2
Just one question: why do you want to do it? - dieter
lets say i have three methods on DAO layer to operate on three different table . in first i am inserting something ,in 2nd i want to update newly generated id of table one . in third also i want to updated something on the basis of newly inserted data of first table. now as i already told , i am not keeping any business logic on dao layer so i am keeping business logic on service layer where i am deciding what to insert or update. so in this if insert or update failed in any method i want to rollback everything . thats why i want to do this - Satish Kumar
This behavior is already covered if you just annotate your service method. - dieter

2 Answers

2
votes

You need to annotate your service method with a REQUIRES_NEW propagation. This would mark the start of transaction. By default, the dao methods if called by this method would inherit the transactional behavior and use the existing transaction.

However, if you want to represent the transactional boundaries in your code, you can annotate them with a REQUIRED (participate in transaction if existing or create a new if doesn't exist) or MANDATORY (participate in transaction if existing, otherwise throw an exception).

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void serviceMethod() {}

@Transactional(propagation = Propagation.REQUIRED)
public void daoMethod1() {}

@Transactional(propagation = Propagation.REQUIRED)
public void daoMethod2() {}
0
votes

You can use the propagation element in the @Transactional annotation with the property Propagation.MANDATORY. With this, the method supports the current transaction or throws an exception if there is no active transaction. So, in your DAO layer, you can do something like this :

@Transactional(propagation=Propagation.MANDATORY)
public void daoMethod() { // some logic }