简体   繁体   中英

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.

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM