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

本文详细解析了在使用Springmvc+Spring+Hibernate4配置时遇到的NoSessionfoundforcurrentthread错误,并通过将配置文件合并及调整组件扫描范围的方法解决了问题。重点在于正确配置事务,确保Controller、Service和Dao之间的事务一致性。

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

[url]http://www.verydemo.com/demo_c143_i3007.html[/url]
在使用Spring mvc + Spring + Hibernate4配置的时候,总是出现 No Session found for current thread,仔细检查applicationContext.xml和dispacter-servlet.xml文件,注解、事务配置都没有问题,纠结好久。

网上搜了很多方法,都不能解决。

有说加上<prop key="hibernate.current_session_context_class">thread</prop>的配置。有说hibernate4要加上的是<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>,经过测试,都不能解决。

看了http://blog.youkuaiyun.com/qq445422083/article/details/8160387帖子之后,觉得说的有道理,还是事务没有装配。

试着把dispacter-servlet.xml中的内容合并到applicationContext.xml中,采用一个配置文件(当然web.xml也要做相应修改),发现并没有报错,问题解决。

但是自己还是喜欢使用两个配置文件,这样结构更清晰。

分析为什么合并到一起就没问题呢,原来spring的context是父子容器,所以会产生冲突,Controller会首先被扫描装配,而此时的Service还没有进行事务的配置,获得的将是原样的Service(没有经过事务装配,故而没有事务处理能力) ,最后才是applicationContext.xml中的扫描设备进行事务处理。

这样就好办了,让两个配置文件各干各的事就可以了。

1 、在Spring主容器中(applicationContext.xml),用<context:exclude-filter/>将Controller的注解过滤掉,不扫描装配它。
<context:component-scan base-package="com">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

2 而在springMVC配置文件中(dispatcher-servlet.xml)将Service和Dao的注解给过滤掉 ,只扫描装配Controller。
<context:component-scan base-package="com">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值