Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction rollback when exception in Spring

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

like image 758
Tea Avatar asked Sep 12 '26 12:09

Tea


1 Answers

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.

like image 159
Adisesha Avatar answered Sep 14 '26 01:09

Adisesha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!