Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put @Transactional? In interface specification or implementation? [duplicate]

What is considered the best practice in placing the @Transactional annotation? Should I annotate the interface method or the implementation?

like image 308
John Manak Avatar asked Apr 05 '11 12:04

John Manak


People also ask

Where should I put @transactional?

Putting @Transactional requires Spring libraries in the API section, which IMHO is not effective. So I prefer to add it in the Implementation where the transaction is running.

Where does the @transactional annotation belong?

The @Transactional annotation belongs to the Service layer because it is the Service layer's responsibility to define the transaction boundaries.

When @transactional is used on top of a class?

In case 1 @Transactional is applied to every public individual method. Private and Protected methods are Ignored by Spring. Spring applies the class-level annotation to all public methods of this class that we did not annotate with @Transactional.

Can we use @transactional at class level?

Annotation Type Transactional. Describes a transaction attribute on an individual method or on a class. When this annotation is declared at the class level, it applies as a default to all methods of the declaring class and its subclasses.


1 Answers

It really all depends on your application architecture, in my opinion. It depends on how you are proxying your classes. If you have your app set to proxy-target-class='true' (in your application context, then your @Transactional information wont be picked up if you annotate the Interface.

Check out The Spring Docs -- "Tips" for more information.

Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.

like image 119
El Guapo Avatar answered Oct 11 '22 16:10

El Guapo