获取org.hibernate.HibernateException:未配置CurrentSessionContext

时间:2020-01-07 14:15:04

标签: java hibernate

当我尝试通过getSessionFactory().getCurrentSession()来获取Hibernate会话时,我已经使用hibernate 5.4创建了一个maven项目并成功创建了DAO。我得到了异常 org.hibernate.HibernateException:没有配置CurrentSessionContext!虽然我已经添加了 <property name="hibernate.current_session_context_class">thread</property> hibernate.cfg.xml 文件中。已经检查了多个论坛,包括这个问题org.hibernate.HibernateException: No CurrentSessionContext configured,但无法解决,

这是hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">onetozero</property>
        <property name="hibernate.connection.url">jdbc:mysql://192.168.0.112:3306/ecdis</property>
        <property name="hibernate.connection.username">root1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="Domain.Route"/>
        <mapping class="Domain.RoutePoint"/>
    </session-factory>
</hibernate-configuration>

HibernateSession类

public class HibernateSession {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}

这就是我通过DAO获取列表的方式

public List<T> list() {
        Session session = HibernateSession.getSessionFactory().getCurrentSession();
        CriteriaQuery<T> query = session.getCriteriaBuilder().createQuery(entityClass);
        query.select(query.from(entityClass));
        return session.createQuery(query).getResultList();
    }

我是Java和Hibernate的新手,也没有使用任何框架的atm,因此也可以进行一些细化。 TIA

1 个答案:

答案 0 :(得分:0)

使用HibernateSession.getSessionFactory()。openSession()而不是getCurrentSession()来获取会话,然后会话工厂将会话绑定到当前上下文,因为您使用的是当前会话上下文类线程而不是JTA。Details here