简体   繁体   中英

Exception in Hibernate console application

I have a simple console application built using Hibernate. It throws an exception when I run it, and I don't know what the problem is.

My code is:

 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();          

    }
}

The exception is:

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)

I suspect your Hibernate configuration is not proper for current session.

Either you are missing hibernate.current_session_context config or using below property in your hibernate configuration

<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocal‌​SessionContext</property>

instate please use below property

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

For more information on Hibernate current session please visit this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM