问题
I am learning Spring and I have some troubles with transaction in Spring.
Here is my code
@Transactional(rollbackFor = Exception.class)
public void createGroupStudent(Student A,Student B,String nameGroup){
try{
//create Group
createGroup(nameGroup);
//createMember
createMember(A,B);
}catch(Exception e){
logger.error(e.getMessage());
}
}
@Transactional(rollbackFor = Exception.class)
public void createGroup(String nameGroup){
try{
repoGroup.save(nameGroup);
}catch(Exception e){
logger.error(e.getMessage());
}
}
@Transactional(rollbackFor = Exception.class)
public void createMember(Student A,Student B){
try{
// function will throw a kind of Exception involve to " error constraint sql oracle " .
//It's my intended
repoMember.save(A,B);
}catch(Exception e){
logger.error(e.getMessage());
}
}
The problem is when function createMember()
throws Exception, transaction alway rollback why? I can't understand what happened! I added try, catch in each method but it didn't work.
Although method createMember()
have trouble while saving to Database (Here i'm using function saveAndFlush()
).I know it and I catch that exception. Parent transaction createGroupStudent()
thinks itself is no problems and commit transaction . But when commit once again method createMember()
will break and throw Exception.I think method createGroup()
won't rollback. But in real, that function rollbacked,all of transactions were rollback? What happened?.
I'm using atomikos transaction.
Thanks so much
回答1:
If you're using hibernate, think of this scenario.
When repoMember.save(A,B); is executed, hibernate session hasn't flushed the session (i.e., executes save sql) util createMember() is finished. When hibernate actually flushes and executes the save sql, that error occurs. That's why you might not able to catch that exception which causes your transaction rollback.
here is link that might be helpful http://hedleyproctor.com/2014/08/understanding-hibernate-session-flushing/
回答2:
If any of the methods throws Exception
, the transaction will rollback. But none of the methods are throwing Exception
. Rethrow the Exception
in catch block, it will work.Check the documentation for Transactional annotation.
来源:https://stackoverflow.com/questions/36759599/transaction-rollback-when-exception-in-spring