使用sessionFactory.getCurrentSession()来获取session,报错为
No Session found for current thread
参考:
http://www.sjsjw.com/kf_other/article/244_20894_27402.asp
说明:
<prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
网上说的这两种解决办法根本就不对, 如果hibernate.cfg.xml里有配的话先删掉,原因请看上边的那个参考链接
解决办法:
spring bean配置文件中加入:
<!--配置事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="exists" read-only="true" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED"/> <!-- hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 配置哪些类的方法进行事务管理 --> <aop:config proxy-target-class="true"> <aop:pointcut id="bussinessService" expression="execution(* com.chaos.service.*.*(..))" /> <aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" /> </aop:config> <aop:config proxy-target-class="true"> <aop:pointcut id="dao" expression="execution(* com.chaos.dao.*.*(..))" /> <aop:advisor pointcut-ref="dao" advice-ref="txAdvice" /> </aop:config>
execution里边的包名根据自己项目来修改,配置完后运行正常