In Spring, as we will see, atomicity of operations

In Spring, how can we make sure that some operations are performed together. If any of these fail, the entire transaction must be canceled. I searched a lot and found @Transactional(propagation = Propagation.REQUIRED) annotations and TransactionTemplate.execute() methods close to my problem. Please clarify and help.

+4
source share
3 answers

Both @Transactional and TransactionTemplate provide atomicity. @Transactional is for declarative transaction management, TransactionTemplate is for managing software transactions. You must choose one.

The idea of ​​transactional propagation applies only to declarative transaction management and defines the behavior of a transaction when it is executed in several ways. Note that Propagation.REQUIRED is the default for Transactional.propagation. This means supporting the current transaction (that is, if the transaction has already been started in the calling method) or creating a new one if it does not exist.

+1
source

@Transactional (distribution = distribution .REQUIRED May solve your problem.

Suppose your Impl has an Excecute.Inside Excecute method, there are other methods M1 (), M2 (), M3 (), M4 (), M5 () .

Maybe you are trying to say that for M1 (), M2 (). M3 (). Methods M4 () Db operation is succedded and finally for M5 () it throws some exception, and M1 () - M5 () all Operation db must be rolled back

 Execute(){ M1(); M2(); M3(); M4(); M5(); 

if (Any error in the transaction of any methods will be rolled back). As a single object, trasaction is used for all ie methods (from M1 to M5) when @Transactional is used (distribution = Distribution .REQUIRED.

}

+1
source

You can create one method that delegates to two database calls, and annotate it with @Transactional , for example

 @Transactional public void atomicOperation(...) { dbCall(); logicOperation(); } 

If one of them does not work, for example, the exception is thrown, the whole operation will be rolled back. Spring reference documentation has dedicated a transaction chapter, for example, there is information on @ Transaction Settings and Transaction Propagation .

0
source

Source: https://habr.com/ru/post/1486547/


All Articles