Hibernate SessionFactory getCurrentSession is not valid without active transaction

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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值