I have a method with @Transaction calling a method with @Transaction( Propagation.REQUIRES_NEW) . Both the transactions are rolled back in case of exception in the parent method.
Parent Transaction:
@Transactional(propagation = Propagation.REQUIRED)
public void test() {
SampleClassParent sampleClassParent = new SampleClassParent();
sampleClassParent.setAddressId(2545L);
sampleClassParent.setUserId(21660742L);
getBaseDao().saveOrUpdate(sampleClassParent);
newTransaction();
// getting an exception purposefully
User user = null;
user.getId(); // Will throw a null pointer exception
}
Nested Transaction:
@Transactional(propagation = Propagation.REQUIRES_NEW)
private void newTransaction(){
SampleClassNested sampleClassNested = new SampleClassNested();
sampleClassNested.setCityId(15747L);
sampleClassNested.setStoreId(5L);
getBaseDao().saveOrUpdate(sampleClassNested);
}
SaveOrUpdate Method: (uses hibernate 3.3.2)
// Wrapper around hibernate method
public void saveOrUpdate(Object entity, boolean delayCommit) {
getSessionFactory().getCurrentSession().saveOrUpdate(entity);
}
All entries are created successfully when no exception is thrown. SampleClassParent and SampleClassNested are Hibernate Entity classes.
Here both the transactions are rolled back, but Ideally, Propagation.REQUIRES_NEW should suspend the existing transaction and create a new transaction. Why?
@Transactional
doesn't work on aprivate
method. See stackoverflow.com/questions/4396284/…. Even forpublic
methods, it only works when called from outside of your class. So your outside caller will have to make two calls. – David Lavender