Reputation: 2597
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
}
}
Upvotes: 1
Views: 1135
Reputation: 400
Yes using try-with-resources is an better option.
But here are few postulates about it:
try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) )
Upvotes: 0
Reputation: 43
As ELLIOT said its better to close sessions manually without relying on any thing or you can use the try block specified above if you are using java 7 or above.
Upvotes: 0
Reputation: 201399
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()) {
// ...
}
Upvotes: 4