Transaction rollback when exception in Spring

青春壹個敷衍的年華 提交于 2019-12-10 10:50:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!