我已经在谷歌上搜索了几个小时,试图找到一个示例,说明如何在使用 DAO 接口(interface)时编写不使用 Springs Hibernate 模板的服务方法。同样让我困惑的是,当我将 @Transactional 注释放在服务层而不是 DAO 中时会发生什么。 服务方法/DAO接口(interface)可以互换吗?
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
感谢您的帮助!
最佳答案
Spring documentation建议完全避免使用 HibernateTemplate,而直接使用 Hibernate API:
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().
并且@Transactional
注释应该始终放在服务层的方法上。这是划分事务的层。
阅读http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#orm-session-factory-setup了解如何设置 session 工厂。完成后, session 工厂可以注入(inject)到您的 DAO 中:
@Repository
public class MyDAO {
@Autowired
private SessionFactory sessionFactory;
...
}
关于java - 不使用hibernate模板的服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10142711/