org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current...

最近遇到了这样的一个错误:

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

原来是在Dao组件的实现类中获取session时引起的,如下的一个类:

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	
    //用户登录功能实现
	public User userLogin(String loginName, String password) {
		System.out.println("调用UserDaoImpl方法userLogin");
		// TODO Auto-generated method stub
		String sql="from User as a where a.loginName=:loginName and a.password=:password";
		Session session=super.getSessionFactory().openSession();
		Query query=session.createQuery(sql);
		query.setString("loginName", loginName);
		query.setString("password", password);
		return (User)query.uniqueResult();		
	}
     
}

继承了类HibernateDaoSupport,在调用该类的Session session=super.getSessionFactory().getCurrentSession()方法获取SessionFactory时就会产生这个错误,这时应将getCurrentSession()方法改为openSession()就会解决这个问题。

猜你喜欢

转载自blog.csdn.net/llc950819/article/details/86670498