简体   繁体   中英

Service methods without using hibernate template

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!

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;

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM