Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which propagation to use in Spring?

I have two different process ( A and B), and A has to start after B, B must not join the A's transaction, B has to wait until A finish its commit.

what propagation should i use ?

Now it is like :

@Transactional
A()

and

@Transactional
B()

Now i use it defult @Transactional, and its not work properly. I think i should use PROPAGATION.

I hope the question is clear. Thanks in advance.

like image 971
mstfdz Avatar asked Sep 03 '15 13:09

mstfdz


People also ask

What is propagation required in Spring transaction?

REQUIRED Propagation REQUIRED is the default propagation. Spring checks if there is an active transaction, and if nothing exists, it creates a new one.

Why @transactional annotation is used in Spring?

The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions, and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions. The default rollback behavior in the declarative approach will rollback on runtime exceptions.

When should I use @transactional?

@Transactional Annotations should be placed around all operations that are inseparable. Using @Transactional transaction propagation are handled automatically.In this case if another method is called by current method,then that method will have the option of joining the ongoing transaction.

When should I use @transactional in Spring boot?

You use @Transcational when concurrent calls on your API can affect each other. Let's say you want to add a Person (you retreive data from somewhere, create a new Person from data and add it to a list of persons).


2 Answers

If B() in its transactional context calling A(), then A() should use REQUIRES_NEW propagation to has its own independent transaction. enter image description here

According to spring framework's Data Access Section:

PROPAGATION_REQUIRES_NEW, in contrast to PROPAGATION_REQUIRED, uses a completely independent transaction for each affected transaction scope. In that case, the underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction’s rollback status.

like image 97
Ali Dehghani Avatar answered Nov 08 '22 15:11

Ali Dehghani


enter image description here

This photo pretty much tells you why you should use REQUIRES_NEW. What you want is invocation always occurs in a new transaction(TX) context.

Note however: Actual transaction suspension will not work on out-of-box on all transaction managers. If you are using JtaTransactionManager, you need javax.transaction.TransactionManager to be made available to it.

like image 20
OPK Avatar answered Nov 08 '22 17:11

OPK