Reputation: 141
I have some problem with rollback transaction when using @Transactional. I have the following code:
@Transactional
public class A{
@Resource
Object obj;
public void insertMultiTable(){
for(Item item:items){
try{
obj.insertTableA();
obj.insertTableB();
} catch(Exception e){
// do somethings...
}
}
}
}
As you can see, i will do insertTableA and insertTableB, my process are success when both finish. I had first and second time is success. But in third, insertTableB will throw Exception, and i just want rollback only this loop with first and second times had been insert in database. How i can do it? Please help...
Upvotes: 1
Views: 4895
Reputation: 18235
Move your logic to another service and mark it with @Transactional(propagation = Propagation.REQUIRES_NEW)
It will make each loop transaction is independent. (IE: Third loop throw exception will only rollback the third loop, leave the first and second loop result committed)
public class SubA {
@Resource
Object obj;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insert(Item i) {
try{
obj.insertTableA();
obj.insertTableB();
} catch(Exception e){
// do somethings...
}
}
}
Now call this service in your A
class
@Transactional
public class A{
@Resource
SubA subA;
public void insertMultiTable(){
for(Item item:items){
subA.insert(item);
}
}
}
Upvotes: 6