Spring3与hibernate4 整合 (No Session found for current thread)

来源:互联网 发布:中国历史故事网软件 编辑:程序博客网 时间:2024/04/28 04:32

最近将hibernate3与spring的整合 ,更换称 hibernate4 出现了一大堆问题。其中一个

原因为:

hibernate4 实现了事务的处理 。spring不在支持HibernateDaoSupport 在hibernate3中我们可以在DAO中继承Spring的HibernateDaoSupport 来实现Session的开启但hibernate4中不在提供其支持,故需要我们自行开启。

在web.xml中需要配置一个Filter

<filter>
<description></description>
<filter-name>openSessionInViewer</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewer</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>openSessionInViewer</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping> 

前提要在Struts 的前面,不然无效

解决二:

在Spring的Applicationcontext.xml中开启注解事务

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 开启通过注解@Transactional管理事务 -->
<!-- 必须开启事务 然后在相应的业务方法使用@Transcation -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />

在相应的方法前使用

@Transactional
public List<TUser> findall() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(" from TUser u order by u.MId desc");
@SuppressWarnings("unchecked")
List<TUser> tuses = query.list();
return tuses;


}

0 0