出现场景:这个问题的出现是在数据库配置了事务的前提下由于hibernate.getCurrentSession() 来进行增删改查,出现的。
原因:因为获取当前的session,这个session的上下文属性值hibernate.current_session_context_class 没有默认值导致的。
解决方式:
直接在spring的application.xml配置文件中设置sessionfactory 时添加hibernate.cfg.xml配置文件:
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:myHibernate.cfg.xml"></property>
</bean>
myHibernate.cfg.xml文件中设置hibernate.current_session_context_class属性
<hibernate-configuration>
<session-factory>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
另一种简单解决方式是重新创立session,不使用hibernate.getCurrentSession()来获取session,使用openSession()来获取session,此时系统会新创立一个线程,当然这个线程是不安全的,要在session操作完成之后,close掉。