java - 不使用hibernate模板的服务方法

标签 java spring hibernate dao hibernate-generic-dao

我已经在谷歌上搜索了几个小时,试图找到一个示例,说明如何在使用 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/

相关文章:

java - 尝试构建 Mave(使用 M2E)出现 classdef 错误

java.awt.print.PrinterException : Printer is not accepting job

json - 如何使用 Katharsis.io 在 Spring Controllers Json 响应中连字符复合属性名称

java - Spring/Hibernate 集成中的 NPE SessionFactory

java - Hibernate Search - 将字段与索引中的另一个字段进行比较

java - JPanel 对象位于底部

java - 如何将主键的 Id 填充到外键

java - 为什么我的 spring @bean 从未实例化?

java - 我可以使用 JPA 将对象类型映射到表吗?

java - 在 Spring Boot 应用程序的 @Transactional 方法中调用 flush()