Reputation: 1533
In Spring how can we make sure that certain operations are always executed together. If any one of them fails, the entire transaction needs to be rolled back. I searched this a lot and found @Transactional(propagation = Propagation.REQUIRED)
annotations and TransactionTemplate.execute()
methods close to my problem. Kindly clarify and help.
Upvotes: 4
Views: 1008
Reputation: 136062
Both @Transactional and TransactionTemplate ensure atomicity. @Transactional is for declarative transaction management, TransactionTemplate is for programmatic transaction management. You should choose one.
The idea of transaction propagation applies only to declarative transaction management and defines a transaction behaviour when it is executed in more than one method. Note that Propagation.REQUIRED is default for Transactional.propagation. It means Support a current transaction (that is if a transaction was already started in the calling method) or create a new one if none exists.
Upvotes: 1
Reputation: 33779
You can create a single method that delegates to the two database calls and annotate that with @Transactional
, e.g.
@Transactional
public void atomicOperation(...) {
dbCall();
logicOperation();
}
If either one fails, e.g. an exception is thrown, the entire operation will rollback. The Spring Reference Documentation has dedicated a chapter for transactions, for example there is information about @Transactional settings and Transaction propagation.
Upvotes: 0
Reputation: 7651
@Transactional(propagation = Propagation.REQUIRED May solve your problem.
Suppose in your Impl there is a method Excecute.Inside Excecute method there are other M1(),M2(),M3(),M4(),M5() methods.
May be you trying to say if for M1(),M2().M3().M4() methods Db operation succedded and at last for M5() it throws some exception then M1() to M5() all db operation should be rollback
Execute(){
M1();
M2();
M3();
M4();
M5();
if(Any error in any methods transaction will be roll back).As single trasaction object is used for all methods i.e(M1 to M5) when @Transactional(propagation = Propagation.REQUIRED is used.
}
Upvotes: 1