【问题标题】:Hibernate SessionFactory getCurrentSession is not valid without active transactionHibernate SessionFactory getCurrentSession 在没有活动事务的情况下无效
【发布时间】:2012-10-10 10:55:41
【问题描述】:

我在 Hibernate 中遇到了一个问题。这是代码。

    Configuration cfg = new Configuration().configure();
    SessionFactory factory = cfg.buildSessionFactory();
    Session session = factory.openSession();

    Transaction trans = session.beginTransaction();
    trans.begin();
    Session session2 = factory.getCurrentSession();
    System.out.println(session2.isConnected());

    trans.commit();

在我的 cfg 文件中

  <session-factory>
    <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433</property>
    <property name="hibernate.connection.username">username</property>
    <property name="connection.password">password</property>
    <property name="connection.pool_size">5</property>
    <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">false</property>
    <mapping resource="Test.hbm.xml"/>
</session-factory>

当我使用上面的代码运行应用程序时,它给了我一个异常说“org.hibernate.HibernateException: isConnected is not valid without active transaction”

我不知道它在内部执行什么行为。请有任何想法。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    如果您查看 SessionFactory.html#getCurrentSession 的 Java 文档

    获取当前会话。确切的“当前”含义的定义由配置为使用的 CurrentSessionContext impl 控制。

    所以你的sessionsession2 是两个不同的会话。因此,您必须在session2 上启动事务才能访问isConnected()

    但是,如果您使用 getCurrentSession() 检索第一个会话,那么第二次 getCurrentSession() 将返回相同的实例。

    Session session = factory.getCurrentSession();//Use getCurrentSession rather than openSession
    Transaction trans = session.beginTransaction();
    trans.begin();
    
    Session session2 = factory.getCurrentSession();//Same session will be returned.
    
    System.out.println(session2.isConnected());
    trans.commit();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-20
      • 2015-05-12
      • 2014-08-19
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 2015-10-19
      相关资源
      最近更新 更多