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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With