我是 hibernate 和 spring 的新手,正在尝试学习 hibernate Interceptor 的使用。 我浏览了社区文档,上面写着......
This interceptor binds a new Hibernate Session to the thread before a method call, closing and removing it afterwards in case of any method outcome. If there already is a pre-bound Session (e.g. from HibernateTransactionManager, or from a surrounding Hibernate-intercepted method), the interceptor simply participates in it.
但是我无法理解我们何时使用它以及为什么使用它?
什么时候像这样创建taskDao?
<bean name="abstractDao" abstract="true">
<property name="hibernateTemplate" ref="taskHibernateTemplate"/>
</bean>
<bean id="taskHibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory" ref="taskSessionFactory"/>
</bean>
<bean id="taskDaoTarget" class="com.xyz.abc.backgroundtask.impl.TaskDao" parent="abstractDao"/>
<bean id="taskDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyTargetClass" value="true"/>
<property name="interceptorNames">
<list>
<value>taskHibernateInterceptor</value>
<value>taskDaoTarget</value>
</list>
</property>
</bean>
什么时候像这样创建taskDao?
<bean name="abstractDao" abstract="true">
<property name="hibernateTemplate" ref="taskHibernateTemplate"/>
</bean>
<bean id="taskDao" class="com.xyz.zbc.backgroundtask.impl.TaskDao" parent="abstractDao"/>
最佳答案
必须使用Hibernate拦截器吗?因为我建议你使用Spring的(基于注释的)Declarative Transaction Management反而。它是许多受支持的底层技术的通用抽象。
基本上,您所做的就是定义一个 TransactionManager Bean,对于使用 JPA 的 Hibernate:
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
没有 JPA:
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
在这两种情况下,激活基于注释的事务:
<tx:annotation-driven />
或者,如果您不使用接口(interface):
<tx:annotation-driven proxy-target-class="true" />
现在使用 @Transactional
注释您的服务层方法或类,您将自动获得在服务方法范围内创建的 session 。
我建议您不要使用 HibernateInterceptor 和 HibernateTemplate,它们都不再是现代的处理方式了。
阅读:
- Declarative Transaction Management
- Using @Transactional
- Implementing DAOs based on plain Hibernate 3 API
- 或者如果您使用 JPA:Implementing DAOs based on plain JPA
看看以前在 Spring 中是如何完成事情的:
关于java - HibernateInterceptor和proxyTargetClass有什么用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330082/