一直很不解这是个什么错,如果去掉这句:
<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>