0

I have a requirement where I need my nested transaction to be a new transaction so that only current transaction will roll-back in case of exception not caller one and I also want to get the saved entity in nested transaction which were saved in upper level transaction.

@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void A(){
//saving  entity x
B();
}

@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = **Propagation.REQUIRES_NEW**, rollbackFor = Exception.class)
public void B(){
//saving some other entity
//fetch previously created entity x

}

Now the problem is When I try to fetch the entity x in B() which was saved in A(), I don't get this.

But If I change the transaction type of B() from Propagation.REQUIRES_NEW to Propagation.REQUIRED it works. Problem in this case is if transaction B is rolled back, transaction A will too, but this is not intended. Please suggest some solution that will solve both of the use-case.

Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
Prashant
  • 57
  • 1
  • 8

1 Answers1

1

When executing B(), your A() transaction is NOT committed. So while fetching elements in B(), you will get what is already saved in database only. your entity x is not there at that point.

1st Question is : why do you need to fetch entity x in B() ? 2nd Question is : if you need entity x in B(), can't you pass it as a parameter ?

Pras
  • 1,068
  • 7
  • 18
  • I am using JPA entity manager to persist the entity So even though it is not committed in database it should be retrieved from session. I can not pass entity as a parameter because I am not using this entity directly in B(), instead I am running a SQL query having few joins which will fetch the data based on previously saved entity. – Prashant May 06 '16 at 12:50
  • It will retrieve from session if it is `Propagation.REQUIRED` ... or you have to change your isolation level as specified in this answer : http://stackoverflow.com/questions/8490852/spring-transactional-isolation-propagation – Pras May 06 '16 at 12:59
  • 1
    just for more precision :REQUIRES_NEW doesn't want to know anything from 'old' context, so it creates a new entity manager with a new hibernate session ... leaving the 'old' one in a open state until it gets committed. – Pras May 06 '16 at 22:01