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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With