This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Lift to ask:@TransactionalWhere exactly do I put the notes?

Should @Transactional be written on DAO layer classes or methods? Or is it better to write in the Service that calls the DAO layer object? Or does it make sense to annotate both layers?

Answer a

I think of transactions as belonging to the Service layer. Because this layer has units of work and use cases. This is the right answer if you have many Dao objects to inject into the Service to work with.

Answer two

In general, I agree with others that transactions are usually started at the Service level (depending on the granularity you need, of course).

However, at the same time, I have also started adding @Transactional (Propagation = Propagation.Mandatory) to my DAO layer (and other layers that do not allow transactions to start but require existing ones), because in callers (such as services), It is easier to detect errors if you forget to start a transaction. If your DAO has force-propagated annotations, you will get an exception stating that there were no active transactions when the method was called.

I also run an integration test in which I check to see if this annotation exists in all beans, and if there is a @Transactional annotation that is not required to propagate in beans that are not part of the service layer, it will fail. This way I can make sure we don’t start a transaction at the wrong level.

Answer three

For database level transactions

I use @Transactional primarily for DAO layer methods. So you can set default(required) specifically for the method

Transactions are not required when the DAO layer gets /select data. But transaction interceptors /AOP also introduce some overhead.

The DAO layer’s insert/update will require the @Transactional annotation.

For application-level transactions

I like to put transactions on business code, and I want to be able to roll back in case of an error.

The article translated from Stack Overflow:stackoverflow.com/questions/1…