title: How to properly close and open a Hibernate session?
body: <p>I have the following method that inserts a large batch of records every few seconds.  After some time of running I get errors like the following:</p>
  
  <blockquote>
    <p>ERROR: Communications link failure</p>
    
    <p>The last packet successfully received from the server was 523
    milliseconds ago.  The last packet sent successfully to the server was
    8 milliseconds ago.</p>
    
    <p>May 16, 2013 9:48:30 AM com.mchange.v2.c3p0.stmt.GooGooStatementCache
    checkinStatement INFO: Problem with checked-in Statement, discarding.</p>
    
    <p>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
    No operations allowed after statement closed.</p>
  </blockquote>
  
  <p><br>
  The code I use to open and close connections is the following:</p>
  
  <pre class="lang-java prettyprint-override"><code>public DataControllerImp() {
      session = HibernateUtil.getSessionFactory().openSession();
  }
  
  @Override
  public void saveMessage(ArrayList&lt;Message&gt; messages) {
      Transaction tx = session.beginTransaction();
  
      for (int i = 0; i &lt; mesages.size(); i++) {
          Message message = messages.get(i);
  
          try {
              session.save(message);
              if (i % 75 == 0) { 
                  // flush a batch of inserts and release memory:
                  session.flush();
                  session.clear();
              }
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } finally {
              session.close();
          }
      }
  
      tx.commit();
  }
  </code></pre>
  
  <p><br>
  I am also using c3p0 connection pooling. My configuration looks like:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;property name="connection.provider_class"&gt;org.hibernate.connection.C3P0ConnectionProvider&lt;/property&gt;        
  &lt;property name="hibernate.c3p0.acquire_increment"&gt;1&lt;/property&gt;
  &lt;property name="hibernate.c3p0.idle_test_period"&gt;300&lt;/property&gt;
  &lt;property name="hibernate.c3p0.min_size"&gt;3&lt;/property&gt;
  &lt;property name="hibernate.c3p0.max_size"&gt;20&lt;/property&gt;
  &lt;property name="hibernate.c3p0.max_statements"&gt;50&lt;/property&gt;
  &lt;property name="hibernate.c3p0.timeout"&gt;300&lt;/property&gt;
  &lt;property name="hibernate.c3p0.acquireRetryAttempts"&gt;1&lt;/property&gt;
  &lt;property name="hibernate.c3p0.acquireRetryDelay"&gt;250&lt;/property&gt;
  </code></pre>
  
  <p><br>
  Am I opening and closing the connections incorrectly?  Please let me know what I can change to stop from receiving this error and halting my program.</p>