用SessionFactory.getCurrentSession执行hibernate操作时,hibernate的操作默认必须包含在一个transaction中,也就是开始要用session.begionTransaction得到一个transaction 实例(譬如tx), 操作结束时在这个实例上进行事务的提交tx.commit或回滚tx.rollback. 如果这些CRUD操作不被包括在一个具体的transaction中,hibernate就会抛出上述异常。
getHibernateTemplate().getSessionFactory().getCurrentSession()的意思是得到当前线程绑定的session,而当前线程绑定的session是通过当前的事务产生的,如果你没有配置事务的话,当前线程threadlocal中就不存在 session,这样就出现no session错误
Solution:
first of all if you want to use getcurrentSession() method you need to add these properties to HibernateProperties:
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
second thing is from the exception, Hibernate3 doesn't allow you to run queries without starting a transaction. you have to add this to your init method before running the query:
sessionFactory.getCurrentSession().beginTransaction();
and of course commit it in the end of your unit of work.
到这这种情况的发生有两种情况:
1,没有配置事物只要在Spring配置文件中添加如下代码:
然后在DAO程序前面加上@Transactional即可。
2,连接数据的配置是否正确,如果连接字符串不正确的话,就不能够创建SessionFactory,也就无从谈起事务了。
在实际的SSH web应用开发中,我们通常用spring来进行事务的管理。我们一般不会在dao层使用transaction,事务被配置在service层上更为合理,因为业务层方法表示逻辑上的一个原子操作。在这种环境下,如果你遇到上述异常,请核查一下service层上有没有配置transaction,transaction有没有打开,service层配置的transaction是否正确。