使用spring4+springMVC+hibernate5 时报错:createQuery is not valid without active transaction;

这里写图片描述

一直很不解这是个什么错,如果去掉这句:

<prop  key="hibernate.current_session_context_class">thread</prop>

就能完美运行,加上这句就报错,实在是头都大了,明明hibernate官方中就是这么定义的:
为了保证一个线程一个Session,即一个线程中使用的Session是同一个对象,一般在获取Session对象时,使用SessionFactory的getCurrentSession()方法。不过,使用该方法获取Session对象,需要在主配置文件中对Session所处的上下文环境,即事务环境进行注册。
经过多方的寻找资料,最后发现问题所在:
原因还是spring中hibernate.current_session_context_class的问题在spring的类LocalSessionFactoryBean源码,方法buildSessionFactory中将hibernate.current_session_context_class设为org.springframework.orm.hibernate5.SpringSessionContext。

完整配置源码

<!-- 建立sessionFactory -->  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">  
                <property name="dataSource"  ref="dataSource"></property>  
                <property name="hibernateProperties">  
                    <props>  
                        <prop key="hibernate.show_sql">true</prop>  
                        <prop key="hibernate.format_sql">true</prop>  
                        <prop key="hibernate.hbm2ddl.auto">update</prop>  
                        <!--添加此句报异常:  
                        在spring的类LocalSessionFactoryBean源码,  
                        方法buildSessionFactory中将hibernate.current_session_context_class设为org.springframework.orm.hibernate5.SpringSessionContext   
                        <prop key="hibernate.current_session_context_class">thread</prop>  
                         -->  
                         <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>  
                    </props>  
                </property>  
                <!-- 自动扫描制定位置下的实体进行映射   -->  
        <property name="packagesToScan" value="cn.cloudclass.bean"/>  
    </bean>  
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值