java - Hibernate 控制台应用程序中的异常

标签 java hibernate console-application

我有一个使用 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.ThreadLocal‌​SessionContext</property>

请使用以下属性

<property name="hibernate.current_session_context_class">thread</property>

有关 Hibernate 当前 session 的更多信息,请访问此 link .

关于java - Hibernate 控制台应用程序中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30107346/

相关文章:

java - 使用可运行的 jar 文件执行时如何解决多线程的 Java 问题?

C# .Net 4.0 控制台应用程序 - 如何在所有线程完成之前保持事件状态?

c# - C# Windows 控制台应用程序如何判断它是否以交互方式运行

c# - 错误 "Missing operand after ' 类农算子”—— 'Bannon' 算子是什么?

java - 在匿名类中限定此名称与简单名称

java - 在 TableViewer 中选择一行

java - 如何在hibernate中执行sql查询

hibernate ,将表与附加列连接起来

java - 从方法(可运行)计时器中获取对象

java - 查询和二级缓存是否同步工作?