Spring3与hibernate4 整合 (No Session found for current thread)
最近将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中开启注解事务
在相应的方法前使用
@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;
}