2

The question is do I have to include @Transactional in every CRUD method in my DAO classes?

So then I add an annotation to a method which causes this exception, but other methods are not causing this exception. Is it because the other methods are simple and execution is not taking too much time?

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
  • 1
    Ideally, it is better to use @Transactional at each service / dao level method and explictly state if it is READONLY or not (default is false). Also, you might want to look at http://stackoverflow.com/questions/26203446/spring-hibernate-could-not-obtain-transaction-synchronized-session-for-current – TheLostMind Aug 31 '16 at 07:14
  • Why some methods cause exception and some not? –  Aug 31 '16 at 07:17
  • Every Spring developer needs to read [this](http://docs.spring.io/autorepo/docs/spring/4.2.x/spring-framework-reference/html/transaction.html) now and then :) – veljkost Aug 31 '16 at 07:26
  • You can read this. http://stackoverflow.com/questions/26203446/spring-hibernate-could-not-obtain-transaction-synchronized-session-for-current – Petar Petrov Aug 31 '16 at 07:30
  • 1
    This question has been [answered](http://stackoverflow.com/questions/1099025/spring-transactional-what-happens-in-background) multiple times [here](https://dzone.com/articles/how-does-spring-transactional) – Sohil Aug 31 '16 at 09:40

1 Answers1

4

General Rule: Add the @Transaction annotation to the method that start (and finish) the unit of work. That is the part of your program that should been handled in on transaction (meaning, that it should be done/saved completely or not at all).

In a web application with ideal design, place the @Transaction annotation at the service that is invoked by the controller. In an other not so ideal web application where the controller invoke more than one service method (and both should must been handled in the same transaction), you have to place the @Transaction annotation at the controller method.

Ralph
  • 118,862
  • 56
  • 287
  • 383