您的位置:首页 > 编程语言 > Java开发

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

2013-09-30 14:27 543 查看

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


修改之后就可以正常提交事务了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐