Reputation: 171
By default, spring framework can rollback when unchecked exception is thrown across the boundary of a transactional method. But in case of transaction propagation, I want to rollback the transaction only if the exception is uncaught by the outmost method (where the tx is started). Is it possible to configure spring this way?
@Transactional
public class OutterA {
@Autowired
private Inner inner;
public void operationA1() {
this.doSomething();
inner.doSomething();
}
public void operationA2() {
this.doSomething();
try {
inner.doSomething();
} catch (Exception e) {
inner.tryAnother();
}
}
public void doSomething() {
}
}
@Transactional
public class Inner {
public void doSomething() {
throw new RuntimeException();
}
public void tryAnother() {
}
}
In above code, I expect operationA1 to be rolled-back because the exception is not caught and causes the end of transaction, while operationA2 succeed because the exception is caught and correctly handled before transaction ends. But spring will rollback both.
// Non-transactional
public class OutterB {
@Autowired
private Inner inner;
public void operationB() {
try {
inner.doSomething();
} catch (Exception ignore) {
}
}
}
In the above code, I expect operationB to be always rolled-back because the transaction is started by Inner
and the exception is thrown across the transaction boundary.
Upvotes: 1
Views: 261
Reputation: 2376
I think you can play with @Transactionl
annotation options like:
rollbackFor, rollbackForClassName
noRollbackFor, noRollbackForClassName
In your code snippet case if you put @Transactional(noRollbackFor = RuntimeException.class)
on your InnerClass
your transaction will be not rollbacked. However putting @Transactional
annotation on a class level will affect each public method in this class, so I recommend you to put this annotation separate on each method and define specific behavior using these options.
Upvotes: 1