• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

openSession() vs getCurrentSession() in same Thread

 
Prakash Pantula
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I'm learning Hibernate and I have a very basic question on Hibernate Session concept. As you know, there are two methods openSession() and getCurrentSession() in SessionFactory and as far as I understand, when we use current_session_context_class = thread, then a session created is bound to the Thread under execution and the thread that created that session. So, if a session is created using openSession() and then call getCurrentSession(), it should return the same session instance.



I see the assertion failing at Assert.assertEquals(session1,session3);

Since the whole execution is under same single main thread, should not session1 and session3 be equal??

Also, I tried to call getCurrentSession() directly as the only call and I still see a Session being returned. Does getCurrentSession() creates a new session, if none existing bound to Thread.

Thanks
 
Prakash Pantula
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody help me understand this?

I looked at the code taken from http://caveatemptor.hibernate.org

Initially I did not include the property in cfg.xml file, as I thought , if none provided, thread is taken by default.

<property name="hibernate.current_session_context_class">thread</property>

However, when I tried to do something like

Session session = HibernateUtil.getSessionFactory().openSession();
Session sessionNew = HibernateUtil.getSessionFactory().getCurrentSession();

got an exception

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:540)
at hello.HelloWorld.main(HelloWorld.java:15)

So, I added the property in file and again tried to create two sessions.

Since the sessions are Thread bound and I'm running in same Main thread, should not both session objects be same and equal

I tried



and I got false in both the cases.


Secondly, if there is no session already created by openSession() method and bound to a context like Thread, if we invode getCurrentSession(), does that create a new Session and bound to Thread.

Or openSession() should have been called prior to getCurrentSession() is called. From

Please clarify.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic