Java Hibernate SessionFactory getCurrentSession在没有活动事务的情况下无效
我在Hibernate中面临一个问题。这是代码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
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();