I'm wondering whether we should use session.close()
when I use c3p0 connection pooling in hibernate? or c3p0 automatically closes after certain time interval? Do I need to just open the session by
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session=factory.openSession();
Because in the following tutorial it doesn't close the session.
What's the correct way?
Edit:
This would be my code
@SuppressWarnings("unchecked")
@Override
public JSONObject getUserDetails(int id) {
long lStartTime = new Date().getTime();
JSONObject obj = new JSONObject();
try(Session session=factory.openSession()) {
Employee emp=(Employee)session.load(Employee.class,id);
if(emp != null) {
obj.put("id", emp.getId());
obj.put("name", emp.getName());
}
long lEndTime = new Date().getTime();
log.info("[ Personal Details ]Time elapsed For Fetching :"+(lEndTime - lStartTime));
} catch (Exception e) {
// TODO: handle exception
}
}
I would recommend that you close
your resources as soon as you can, that way the connection will be returned to the pool faster. You can also use the try-with-resources
Statement to make sure that happens.
SessionFactory factory = HibernateUtil.getSessionFactory();
try (Session session = factory.openSession()) {
// ...
}