Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple transaction calls made from Controller

I have a situation where lets say I have two services

AccountService 
CustomerService

Both annotated with @Transactional with some createXXX() methods.

Now from my AccountController lets say I have a method where I would first call createAccount() and once I get back the Account-ID from createAccount() I may then call createCustomer() (To create a Customer and also update Account-ID from Account on the Customer)

If for some reason createCustomer() fails I will be left with a polluted state where Account has already been persisted but no Customer created.

Should I resolve this with a TransactionSynchronizationManager OR how should I handle this situation?

like image 697
FakirTrappedInCode Avatar asked Nov 07 '22 05:11

FakirTrappedInCode


1 Answers

Spring transaction use REQUIRES propagation level by default (see org.springframework.transaction.annotation.Transactional#propagation). It means, Spring will not create a new transaction unless there is an existing one. Use this feature: you can either annotate controller's method with @Transactional or create a new service that will trigger the top-level transaction. The idea is that as soon as you created one transaction, service calls will not create new ones. As a result, you have just one transaction that can either successfully commit or fail.

like image 116
Roman Proshin Avatar answered Nov 15 '22 11:11

Roman Proshin