2012-10-10 67 views
1

我在Hibernate中遇到了一个问题。这是代码。Hibernate SessionFactory getCurrentSession在没有活动事务的情况下无效

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也不是没有积极的交易有效”

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

回答

2

如果你看看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(); 
+0

非常感谢您为您提供宝贵的信息。 –

相关问题