在SSH框架的项目中,做数据库操作,
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
但是getCurrentSession()时就会报错:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
报错原因是在dao操作时,使用了原生的SQL语句查询,之前没有报错是因为一直用的是Hql语句,用criteria或者query对象,用HibernateTemplate操作也不报错。解决方法:
如果使用hibernate的getCurrentSession()获得对象,对查询语句也需要开启事务,不然就会报出异常(org.hibernate.HibernateException: createQuery is not valid without active transaction)
需将getCurrentSession()改为openSession()或
如果采用jdbc独立引用程序配置如下:<prop key="hibernate.current_session_context_class">thread</prop>