Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open and close Hibernate session

Tags:

java

hibernate

This is how I get a Hibernate Session and create query.

HSession.getSession().createQuery("query here").executeUpdate();

AND

Critaria cr=HSession.getSession().createCritaria(..).. ;

HSession is where my Session factory is located and getSession() method returns a new session

(getSessionFactory().openSession();)

I want to know whether

  • After calling cr.list(); Is the session is still alive?
  • If alive, getting this criteria or executing a query way is not good? and
  • Creating a Session as

    Session s=HSession.getSession();
    s.createCriteria...

    Is the way to use the session and close it using s.close(); ?

like image 726
Débora Avatar asked Nov 17 '11 09:11

Débora


People also ask

How do I close an open session in Hibernate?

It all depends on how you obtain the session. if you use sessionFactory. getCurrentSession() , you'll obtain a "current session" which is bound to the lifecycle of the transaction and will be automatically flushed and closed when the transaction ends (commit or rollback). if you decide to use sessionFactory.

What is open session in Hibernate?

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.


2 Answers

Yes, the session will be alive until you close it. You can perform multiple operations against a session, but only close() will close it.

In your case, it looks like the sessions are controlled by whatever HSession is. You'll need to look at that to see if any transactions are performed, how the sessions are managed, etc.

like image 154
skaffman Avatar answered Oct 28 '22 05:10

skaffman


I read about this today ... it said "A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends." So according to this: If you have a transaction wrapped around it (and you should have i guess) and call transaction.commit() ... the session is closed.
In your case it should still be open.

Please correct me if I'm wrong with this ... ! :)

like image 29
gilaras Avatar answered Oct 28 '22 05:10

gilaras