I'm developing basic CRUD APIs using Micronaut, wherein a service (let's call this #1) calls another service (let's call this #2) which in turns calls the save method of the CrudRepository.
To define atomic work units, I'm using the @Transactional annotation. Should I define #1 to be @Transactional, or #2 to be @Transactional, or both as @Transactional? In case if I annotate both with the @Transactional annotation, how would Micronaut handle these?
So far, I haven't been able to decipher how the annotation works.
CodePudding user response:
If #2 may be called independently as well as called by #1, then both should be @Transactional
with propagation = Propagation.REQUIRED
. Therefore, if #2 is called directly a transaction is created, and if #1 is called, the transaction created for #1 is used for #2.
CodePudding user response:
To define atomic work units, I'm using the @Transactional annotation. Should I define #1 to be @Transactional, or #2 to be @Transactional, or both as @Transactional? In case if I annotate both with the @Transactional annotation, how would Micronaut handle these?
It isn't clear if there is any transactional behavior going on in #1. If the answer is "yes", then the answer to your question is "yes". If there is no transactional behavior in #1, then marking it with @Transactional
may not make sense.
If you do mark #1 with @Transactional
, then by default when #1 calls #2, #2 will participate in the same transaction as #1. It is possible to have those 2 operate in separate transactions if the propogation level for #2 was configured to be REQUIRES_NEW
but it doesn't sound like that is what you are likely looking for.