Hibernate SessionFactory getCurrentSession is not valid without active transaction

来源:互联网 发布:手机可以恢复u盘数据吗 编辑:程序博客网 时间:2024/05/18 17:04

I am facing one problem in Hibernate. Here is the code.

    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();

And in my cfg file

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

when i run the application with above code it is giving me an Exception saying “org.hibernate.HibernateException: isConnected is not valid without active transaction

I don’t know what behavior its performing internally. Any idea’s please.

if you look at the Java doc of SessionFactory.html#getCurrentSession

Obtains the current session. The definition of what exactly “current” means controlled by the CurrentSessionContext impl configured for use.
So your session and session2 are two different sessions. So you will have to start the transaction on session2 to access isConnected().

However if you used getCurrentSession() to retrieve first session then second time getCurrentSession() will return you the same instance.

Session session = factory.getCurrentSession();//Use getCurrentSession rather than openSessionTransaction trans = session.beginTransaction();trans.begin();Session session2 = factory.getCurrentSession();//Same session will be returned.System.out.println(session2.isConnected());trans.commit();
0 0
原创粉丝点击