Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Need to clear the difference between hibernate opensession and currentsession method

 
Akshay Ajmani
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<property name="current_session_context_class">thread</property> is used in assocation with currentSession()
This means that if you have a thread in which you create a Session s1 and you dont close s1 and you create another session s2
and then s2 wud point to s1

here in the following code snippet, value1 and value2 are same

but if s1 is closed then s2 would be different

for eg :

public static void main(String[] a)
{
Session session=HibernateUtil.currentSession();
session.beginTransaction();
Iterator itr=session.createCriteria(SmHostBean.class).list().iterator();
//session.getTransaction().commit(); <!-- session not closed-->
SmHostBean smHostBean=null;
while(itr.hasNext())
{
smHostBean=(SmHostBean)itr.next();
}

System.out.println("session in main thread=="+session); //value1
Sessionsession1=HibernateUtil.currentSession();
System.out.println("session in main thread=="+session1); //value2

}


but if in this example i had used opensession then i would have got different sessions i.e s1 and s2 would b diff when s1 is open
in openSession() session.close has to be done explicitly
in getcurrentsession() session is closed when transaction completes

Is my understanding of the two methods correct.

Kindly help
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!