【问题标题】:Hibernate : No CurrentSessionContext configured休眠:未配置 CurrentSessionContext
【发布时间】:2013-12-14 10:46:18
【问题描述】:

由于某个地方的一些愚蠢错误,我被卡住了,但无法弄清楚!

休眠 4.2.6

这个问题我已经提到过,之前问过好几次,比如here

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
    "-//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">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <property name="show_sql">true</property>

        <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>

        <mapping resource="Event.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

Event.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="com.db.pojo.Event" table="Events">

        <id name="id" column="Id">
            <generator class="native"></generator>
        </id>
        <property name="title" column="Title"></property>

        <property name="date" column="Date" type="timestamp"></property>

    </class>

</hibernate-mapping>

HibernateUtil

package com.db.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        // TODO Auto-generated method stub

        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");

        ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        return configuration.buildSessionFactory(serviceRegistryBuilder
                .buildServiceRegistry());
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

每当我尝试这个时:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

我明白了:

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988)
    at test.EventManager.createAndStoreEvent(EventManager.java:27)
    at test.EventManager.main(EventManager.java:17)

在我的个人笔记本电脑上执行后编辑

  1. 如果我在 cfg 文件中使用“线程”,代码运行良好
  2. 如果我使用 'ThreadLocalSessionContext',我会得到以下异常(请注意,即使控制台上的输出现在也比之前运行的要大) - 是不是 'ThreadLocalSessionContext' 类是在 3.0 版本中不存在(我试图在 API 中找到,但该站点没有旧 API

现在我对 dtd 持怀疑态度 - 即使指定了 SYSTEM,Hibernate 3.0 jar 是否在某处被引用而本地的 jar 被忽略?在 Internet 访问受限的机器上执行代码时,我遇到了上一个异常(没有当前上下文)。但是当我在我的个人笔记本电脑上执行同样的操作时:

eventDesciption : Team eventDate : 2013-12-12
Nov 28, 2013 8:55:59 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Nov 28, 2013 8:55:59 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: resources/Event.hbm.xml
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Nov 28, 2013 8:56:00 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Nov 28, 2013 8:56:00 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Nov 28, 2013 8:56:00 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Nov 28, 2013 8:56:00 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Nov 28, 2013 8:56:00 PM org.hibernate.internal.SessionFactoryImpl buildCurrentSessionContext
ERROR: HHH000302: Unable to construct current session context [org.hibernate.context.ThreadLocalSessionContext]
org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.context.ThreadLocalSessionContext]
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:152)
    at org.hibernate.internal.SessionFactoryImpl.buildCurrentSessionContext(SessionFactoryImpl.java:1544)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:516)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
    at com.db.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
    at com.db.util.HibernateUtil.<clinit>(HibernateUtil.java:9)
    at test.EventManager.createAndStoreEvent(EventManager.java:27)
    at test.EventManager.main(EventManager.java:17)
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.context.ThreadLocalSessionContext
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:319)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:149)
    ... 7 more

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988)
    at test.EventManager.createAndStoreEvent(EventManager.java:27)
    at test.EventManager.main(EventManager.java:17)

【问题讨论】:

    标签: hibernate hibernate-mapping hibernate-4.x


    【解决方案1】:

    尝试改变

    Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 
    

    到:

    Session session = HibernateUtil.getSessionFactory().openSession();
    

    【讨论】:

    • 这解决了问题,但又引发了另一个问题。如果以这种方式使用,则必须手动关闭会话以避免打开太多会话。
    【解决方案2】:

    据我所知,您的配置不适合当前会话。而不是

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

    使用

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

    有关这方面的更多信息,请访问此链接:

    http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/architecture.html#architecture-current-session

    特别是阅读最后一段的最后几行。

    对于使用 Hibernate 4.1 的用户,

    <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
    

    参考:https://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/context/internal/ThreadLocalSessionContext.html

    【讨论】:

    • 在发布这个问题之前,我已经参考了类似的帖子,并且尝试了两种方法都徒劳无功,问题是别的!
    • @KaliyugAntagonist 当您只写thread 而不是org.hibernate.context.ThreadLocal‌​SessionContext 时会出现什么异常?
    • 我已经编辑了我的帖子 - 我在不同的机器上得到了不同的行为。
    • Hibernate 教程中指出“线程”是设计和原型需要考虑的值,但不适用于生产。于是我去了hibernate库(v4.3),发现org.hibernate.context.ThreadLocal‌​SessionContext这个类不存在。相反,有一个 org.hibernate.context.internal.ThreadLocal‌​SessionContext 类对我有用。
    • @Solostaran14,感谢您指出这一点。更新了答案。
    【解决方案3】:

    您需要更改您的属性:

    org.hibernate.context.internal.ThreadLocalSessionContext线程

    【讨论】:

      【解决方案4】:

      我知道这是一篇旧帖子,但以防万一有人像我一样来到这里 - 这是有效的

      package com.spring.util;
      
      import org.hibernate.SessionFactory;
      import org.hibernate.cfg.Configuration;
      
      public class HibernateUtil {
      
      private static HibernateUtil instance = new HibernateUtil();
      
      private SessionFactory sessionFactory;
      
      private HibernateUtil(){
          this.sessionFactory = buildSessionFactory();
      }
      
      private synchronized static SessionFactory buildSessionFactory() {
          return new Configuration().configure().buildSessionFactory();
      }
      
      public static HibernateUtil getInstance() {
          if(instance == null){
              return new HibernateUtil();
          }
          return instance;
      }
      
      public SessionFactory getSessionFactory() {
          return sessionFactory;
      }
      
      }
      

      现在调用它非常简单:

      SessionFactory sessionFactory = HibernateUtil.getInstance().getSessionFactory();
      

      下一步将如下所示:

      public void saveOrUpdate(MyObject myObj) {
          Session session = sessionFactory.getCurrentSession();
          session.beginTransaction();
          session.saveOrUpdate(myObj);
          session.getTransaction().commit();
      }
      

      还要确保 hibernate.cfg.xml 在 src/main/resources 文件夹中。

      【讨论】:

      • 这还是有问题的。得到错误 org.hibernate.HibernateException: No CurrentSessionContext configured!
      • 好的,不知道发生了什么,因为我看不到完整的堆栈跟踪,但也许这篇文章会对你有所帮助:stackoverflow.com/questions/7281045/…
      【解决方案5】:

      对于休眠 4.x,您需要使用 org.hibernate.context.internal.ThreadLocalSessionContext 而不是 org.hibernate.context.ThreadLocalSessionContext .

      但是,您可以将属性设置为 thread 而不是 Thread

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

      【讨论】:

        【解决方案6】:

        尝试改变

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        

        到:

        Session session = HibernateUtil.getSessionFactory().openSession();
        

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 2014-12-27
        • 1970-01-01
        • 1970-01-01
        • 2022-08-05
        • 2010-11-08
        • 2020-11-18
        • 2015-07-28
        相关资源
        最近更新 更多