我有一个使用 Hibernate 构建的简单控制台应用程序。运行的时候就抛出异常,不知道是什么问题。
我的代码是:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class TestEmployee {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
config.configure("hibernate.cfg.xml");
new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
Employee tom = new Employee();
mehdi.setEmpId(100);
mehdi.setEmpName("Tom Hani");
session.save(mehdi);
session.getTransaction().commit();
}
}
异常(exception)情况是:
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured! at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:685) at com.Hibernate.chapter1.TestEmployee.main(TestEmployee.java:20)
最佳答案
我怀疑您的 Hibernate 配置不适合当前 session 。
您缺少 hibernate.current_session_context 配置或在 hibernate 配置中使用以下属性
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
请使用以下属性
<property name="hibernate.current_session_context_class">thread</property>
有关 Hibernate 当前 session 的更多信息,请访问此 link .
关于java - Hibernate 控制台应用程序中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30107346/