Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hibernate SessionFactory getCurrentSession在没有活动事务的情况下无效_Java_Hibernate - Fatal编程技术网

Java Hibernate SessionFactory getCurrentSession在没有活动事务的情况下无效

Java Hibernate SessionFactory getCurrentSession在没有活动事务的情况下无效,java,hibernate,Java,Hibernate,我在Hibernate中面临一个问题。这是代码 Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Transaction trans = session.beginTransaction(); trans.begin

我在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>

com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc:sqlserver://localhost:1433
用户名
密码
5.
org.hibernate.dialogue.sqlserverdialogue
线
真的
假的
当我用上面的代码运行应用程序时,它会给我一个异常,说“org.hibernate.hibernateeexception:isConnected在没有活动事务的情况下无效”


我不知道它在内部表现出什么样的行为。任何想法都可以

如果您查看

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

因此,您的
会话
会话2
是两个不同的会话。因此,您必须在
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();