Java – Transaction rollback when exception in Spring

commitjavarollbackspringtransactions

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

Best Answer

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.