您的位置:首页 > 其它

Hibernate SessionFactory getCurrentSession is not valid without active transaction

2015-09-21 13:23 453 查看
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 openSession
Transaction trans = session.beginTransaction();
trans.begin();

Session session2 = factory.getCurrentSession();//Same session will be returned.

System.out.println(session2.isConnected());
trans.commit();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate session