Where does the @Transactional annotation belong?

Should you place the @Transactional in the DAO classes and/or their methods or is it better to annotate the Service classes which are calling using the DAO objects? Or does it make sense to annotate both "layers"?


I think transactions belong on the Service layer. It's the one that knows about units of work and use cases. It's the right answer if you have several DAOs injected into a Service that need to work together in a single transaction.


In general I agree with the others stating that transactions are usually started on the service level (depending on the granularity that you require of course).

However, in the mean time I also started adding @Transactional(propagation = Propagation.MANDATORY) to my DAO layer (and other layers that are not allowed to start transactions but require existing ones) because it is much easier to detect errors where you have forgotten to start a transaction in the caller (eg the service). If your DAO is annotated with mandatory propagation you will get an exception stating that there is no active transaction when the method is invoked.

I also have an integration test where I check all beans (bean post processor) for this annotation and fail if there is a @Transactional annotation with propagation other than Mandatory in a bean that does not belong to the services layer. This way I make sure we do not start transactions on the wrong layer.


Transactional Annotations should be placed around all operations that are inseparable.

For example, your call is "change password". That consists of two operations

  • Change the password.
  • Audit the change.
  • Email the client that the password has changed.
  • So in the above, if the audit fails, then should the password change also fail? If so, then the transaction should be around 1 and 2 (so at the service layer). If the email fails (probably should have some kind of fail safe on this so it won't fail) then should it roll back the change password and the audit?

    These are the kind of questions you need to be asking when deciding where to put the @Transactional .

    链接地址: http://www.djcxy.com/p/49976.html

    上一篇: Microsoft .NET 4.0完整框架和客户端配置文件之间的差异

    下一篇: @Transactional注释属于哪里?