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

问: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>

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值