Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to close database connection in hibernate?

Firstly it may sound like a duplicate question but i didn't get solution i was expecting so I am posting this new question?I have started learning hibernate a couple of days ago.I am stuck on this 1 thing:

Here is my code:

public static void open_connection()

sessionfactory=new Configuration().configure().buildSessionFactory();
Listsession = sessionfactory.openSession();
}

public  List select(String qry)
{ 
    open_connection();  
    Listsession.beginTransaction();
    query =Listsession.createQuery(qry);
    list=query.list();
    Listsession.getTransaction().commit();
    Listsession.close();
    sessionfactory.close();
    }

Q1. I have closed the sessionfactory when a query has run.Is it a good approach?I want to close database connection when we don't need it as we do in JDBC(My teacher taught me that).

Q2. Should I close connection when user is getting logout from my site?

Q3. Will sessionfactory.close(); also destroy my session variable(session.setattribute("user",ur);).

Q4. Does Listsession.getTransaction().commit(); also close the transaction?

I want to know this because many times i run my project on netbeans i am getting null pointer exception but when i run same project online i don't get null pointer exception and i think this happens because openconnection is called everytime i run my project. Sorry for posting so many questions as i couldn't get exact answers i was looking for.

like image 836
Fresher Avatar asked Jul 23 '14 09:07

Fresher


1 Answers

1.You should close the Session but not SessionFactory
2.You are already closing Session after executing query, so where is the point of again closing when logout from site ?
3.HttpSession is different from Session in Hibernate. HttpSession for storing attributes for maintaining user sequence of requests. But Session in Hibernate to interact with Database only. So closing Session in Hibernate doesn't reflect on HttpSession.
4.If you are using openSession(), you should close the session manually.But if you are using getCurrentSession(), you don't need to bother of it, once transaction committed, session will be closed automatically.
Hope it helps,

like image 185
Mr.Chowdary Avatar answered Oct 01 '22 06:10

Mr.Chowdary