0

I have been googling for several hour now trying to find an example on how to write a service method that doesn't use Springs Hibernate Template while using a DAO interface. Something that is also confusing me is what happens when I put the @Transactional annotation in the service layer as opposed the DAO. Are the Service methods/DAO interfaces interchangeable?

Here is an example where the @Transactional is in the DAO

Here is one with the @Transactional in the Service Layer but using hibernate templates

Thanks for your help!

dlinx90
  • 855
  • 4
  • 14
  • 24

1 Answers1

2

The Spring documentation recommends avoiding HibernateTemplate completely, and use the Hibernate API directly instead:

NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate3 style of coding data access objects instead, based on SessionFactory.getCurrentSession().

And the @Transactional annotation should always be put on methods of the service layer. This is the layer that demarcates transactions.

Read http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#orm-session-factory-setup to understand how to setup a session factory. Once done, the session factory can be injected in your DAOs:

@Repository
public class MyDAO {
    @Autowired
    private SessionFactory sessionFactory;

    ...
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thank you, that helped a lot but I'm still a bit confused about what the difference is between the service methods and the DAOs purposes. Any chance you could give me (or point me in the direction) of an example of how they interact with each other? – dlinx90 Apr 13 '12 at 15:29
  • Read this answer and the comments following it: http://stackoverflow.com/questions/8754840/best-way-to-develop-service-layer-in-java/8754873#8754873 – JB Nizet Apr 13 '12 at 15:32
  • That's exactly the information I was looking for! Thank you. I have a followup question regarding what you said about the service layer calling multiple DAOs. Will I write a separate DAO for each task I wish to perform? Also I was wondering a bit off topic, what is the use of creating a Dao then a DaoImplementation? Thanks! – dlinx90 Apr 13 '12 at 15:54
  • Just as for every other class, you'll group methods that logically go together in a single DAO. For example, you could group all the methods concerning a given entity, or set of entities, in a single DAO. An interface is useful mainly for unit testing, in order to be able to mock the DAO and test the services that depend on it. – JB Nizet Apr 13 '12 at 19:33