SpringMVC3+Hibernate4问题:org.hibernate.HibernateException: No Session found for current thread

本文详细介绍了如何在Spring框架中配置Hibernate实现会话管理,并解决了在DAO层注入sessionFactory后无法获取Session的问题。同时,文章还讨论了在集成Spring和Hibernate后遇到的事务提交问题及其解决方案,包括调整Spring容器配置以确保事务的正确执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问:1:org.hibernate.HibernateException: No Session found for current thread

解决方法:
在web.xml中添加openSessionInViewFilter
<filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
</filter>
<filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>*.do</url-pattern>
</filter-mapping>

注意:singleSession为true;不要漏掉filter-mapping.

这样在dao中注入sessionFactory;就能通过this.sessionFactory.getCurrentSession()方法取到Session了。

问题2:解决上述问题后,hibernate不能自动提交事务,更新数据到数据库中

解决方法:
原因:spring的主配置文件和springmvc的配置文件,重复扫描事务和bean的注解,导致失效。
ServletContextListener产生的是父容器,springMVC产生的是子容器,子容器中的Controller进行装配时,装配了扫描到的@Service注解的实例,而非由父容器进行初始化的实例,所以此时得到的Service是没有经过事务加强处理的,故而没有事务处理能力。

正确配置如下:
主配置文件:(使用的是默认规则)
<context:component-scan base-package="com" >
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
</context:component-scan>
springmvc配置文件:use-default-filters="false"(不使用默认规则,自定义规则)
<context:component-scan base-package="com" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
</context:component-scan>

修改之后就可以正常提交事务了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值