Syed
Syed

Reputation: 2597

sessions should be closed in hibernate when we use c3p0 connection pooling?

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.

http://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-connection-pool-configuration-with-c3p0-example/

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

Answers (3)

Gurpreet Singh
Gurpreet Singh

Reputation: 400

Yes using try-with-resources is an better option.

But here are few postulates about it:

  1. Any exception thrown from try-with-resources statements are suppressed.
  2. You can use catch, finally block as with normal try-catch.
  3. You can declare multiple resources separated by semi-colon inside the try-with-resources like
try (
        java.util.zip.ZipFile zf =
             new java.util.zip.ZipFile(zipFileName);
        java.io.BufferedWriter writer = 
            java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    )
  1. It closes the resources after ending of try block first i.e. if any exception comes from try block or not. After that it executes catch, finally block.
  2. Your resource which is declared inside try-with-resource statement must implement the AutoCloseable or Closeable Interface.

Upvotes: 0

FaheemFayaz
FaheemFayaz

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

Elliott Frisch
Elliott Frisch

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

Related Questions