java - 运行 jsp 时无法转换为 hibernate.HibernateSession
问题描述
我正在尝试编写我的第一个 Hibernate 项目。但我有一个例外。
java.lang.ClassCastException:org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction 不能转换为 hibernate.HibernateSession
这就是我编写会话方法的方式。
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class HibernateSession {
static Connection.NewHibernateUtil hibernateutil;
static SessionFactory sessionfactory;
static Session session;
static Transaction transaction;
private HibernateSession() {
}
public static HibernateSession getHSConnection() {
if (transaction == null) {
session = Connection.NewHibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
}
return (HibernateSession) transaction;
}
public static void closeHSConnection() {
if (transaction != null) {
session.flush();
transaction.commit();
}
session.close();
}
}
这段代码有错误吗?
解决方案
当对象是完全不同的类的实例时,您不能将对象强制转换为您的类 (JDBCTransaction)
return (HibernateSession) transaction; // this is the error