title: How to solve Google CloudSQL 8 hours timeout?
body: <p>I'm working in an app with Google Cloud SQL. I'm using Hibernate 4.2.0.Final and I've noticed that after 8 hours of inactivity my connection is closed. I've been searching on the Internet and I couldn't find anything effective to solve this issue. All the information I've found is summarized in these items:</p>
  
  <ul>
  <li>Use a connection pool where I should specify a higher timeout. I've tried with c3p0 and DBCP 2.1.1 libraries but none of them solved the issue.</li>
  <li>Open a connection before some query and then close it after that. The problem is that I would like to use the EntityManager in order to use queries with entities.</li>
  </ul>
  
  <p>Here it's what I've done with DBCP 2.1.1 (<a href="http://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2/2.1.1" rel="nofollow">http://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2/2.1.1</a>). The problem is that Goggle App Engine logs show an <code>ExceptionInInitializerError</code> when I try to use <code>findAll</code> in my <code>PersistenceService</code>. The logs also show that my <code>DataSource</code> (see below) cannot be cast to <code>String</code>. I don't understand why.</p>
  
  <p>This is the <code>PersistenceService</code> I'm using right now</p>
  
  <pre><code>package co.peewah.ems.utils;
  
  import com.google.appengine.api.utils.SystemProperty;
  
  import java.beans.PropertyVetoException;
  import java.io.IOException;
  import java.sql.SQLException;
  import java.util.AbstractMap.SimpleEntry;
  import java.util.Date;
  import java.util.GregorianCalendar;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.Properties;
  import java.util.UUID;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  import javax.persistence.Query;
  import javax.persistence.TypedQuery;
  import javax.persistence.criteria.CriteriaQuery;
  import javax.persistence.criteria.Root;
  
  import org.hibernate.cfg.AvailableSettings;
  
  
  /**
   *
   * @author Muacito
   */
  public class PersistenceService
  {
      private static final EntityManagerFactory EMF = createEntityManagerFactory();
  
      private static EntityManager entityManager = EMF.createEntityManager();
  
      private static EntityManagerFactory createEntityManagerFactory()
      {
          //String mode = "";
          /*
          if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development)
          {
              mode = "dev.";
          }
          */
  
          Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;();
  
          //Properties properties = new Properties();
  
          //properties.put("javax.persistence.jdbc.driver", System.getProperty("persistence." + mode + "db.driver"));
          //properties.put("javax.persistence.jdbc.url", System.getProperty("persistence." + mode + "db.url"));
          //properties.put("javax.persistence.jdbc.user", System.getProperty("persistence." + mode + "db.user"));
          //properties.put("javax.persistence.jdbc.password", System.getProperty("persistence." + mode + "db.password"));
          try
          {
              properties.put(AvailableSettings.DATASOURCE, DataSource.getInstance());
          } catch (IOException | SQLException | PropertyVetoException e)
          {
               e.printStackTrace();
          }
  
  
          System.out.println("----------------------------");
          System.out.println("----------------------------");
          System.out.println(properties);
          System.out.println("----------------------------");
          System.out.println("----------------------------");
  
          return Persistence.createEntityManagerFactory("Demo", properties);
      }
  
      private static EntityManager getEntityManager()
      {
          if (!PersistenceService.entityManager.isOpen())
          {
              PersistenceService.entityManager = PersistenceService.EMF.createEntityManager();
          }
  
          return PersistenceService.entityManager;
      }
  
      public static &lt;T&gt; void create(T entity)
      {
          try
          {
              if (entity.getClass().getMethod("getId").invoke(entity) == null)
              {
                  entity.getClass().getMethod("setId", String.class).invoke(entity,
                          UUID.randomUUID().toString().replace("-", ""));
              }
  
              if (entity.getClass().getMethod("getCreated").invoke(entity) == null)
              {
                  entity.getClass().getMethod("setCreated", Date.class).invoke(entity,
                          GregorianCalendar.getInstance().getTime());
              }
  
              getEntityManager().getTransaction().begin();
  
              getEntityManager().persist(entity);
  
              getEntityManager().flush();
  
              getEntityManager().getTransaction().commit();
  
          } catch (Exception ex)
          {
              Logger.getLogger(PersistenceService.class.getName()).log(Level.SEVERE, null, ex);
              getEntityManager().getTransaction().rollback();
          }
      }
  
      public static &lt;T&gt; void edit(T entity)
      {
          try
          {
              if (entity.getClass().getMethod("getUpdated").invoke(entity) == null)
              {
                  entity.getClass().getMethod("setUpdated", Date.class).invoke(entity,
                          GregorianCalendar.getInstance().getTime());
              }
  
              getEntityManager().getTransaction().begin();
  
              getEntityManager().merge(entity);
  
              getEntityManager().flush();
  
              getEntityManager().getTransaction().commit();
          } catch (Exception ex)
          {
              Logger.getLogger(PersistenceService.class.getName()).log(Level.SEVERE, null, ex);
              getEntityManager().getTransaction().rollback();
          }
      }
  
      public static &lt;T&gt; void remove(T entity)
      {
          try
          {
              getEntityManager().getTransaction().begin();
  
              getEntityManager().remove(entity);
  
              getEntityManager().flush();
  
              getEntityManager().getTransaction().commit();
  
          } catch (Exception ex)
          {
              Logger.getLogger(PersistenceService.class.getName()).log(Level.SEVERE, null, ex);
              getEntityManager().getTransaction().rollback();
          }
      }
  
      public static &lt;T&gt; List&lt;T&gt; filter(Class&lt;T&gt; entityClass, String query, SimpleEntry&lt;String, Object&gt;... parameters)
      {
          TypedQuery&lt;T&gt; typedQuery = getEntityManager().createQuery(query, entityClass);
  
          for (SimpleEntry&lt;String, Object&gt; param : parameters)
          {
              typedQuery.setParameter(param.getKey(), param.getValue());
          }
  
          return typedQuery.getResultList();
      }
  
      public static &lt;T&gt; T find(Class&lt;T&gt; entityClass, Object id)
      {
          T entity = getEntityManager().find(entityClass, id);
  
          return entity;
      }
  
      public static &lt;T&gt; List&lt;T&gt; findBy(Class&lt;T&gt; entityClass, String criteria, Object value)
      {
          String c = criteria.replaceFirst(criteria.charAt(0) + "", (criteria.charAt(0) + "").toLowerCase());
  
          TypedQuery&lt;T&gt; query = getEntityManager().createNamedQuery(entityClass.getSimpleName() + ".findBy" + criteria,
                  entityClass);
          query.setParameter(c, value);
  
          return query.getResultList();
      }
  
      public static &lt;T&gt; List&lt;T&gt; findAll(Class&lt;T&gt; entityClass)
      {
          CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
          cq.select(cq.from(entityClass));
  
          return getEntityManager().createQuery(cq).getResultList();
      }
  
      public static &lt;T&gt; List&lt;T&gt; findRange(Class&lt;T&gt; entityClass, int[] range)
      {
          CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
          cq.select(cq.from(entityClass));
          Query q = getEntityManager().createQuery(cq);
          q.setMaxResults(range[1] - range[0] + 1);
          q.setFirstResult(range[0]);
  
          return q.getResultList();
      }
  
      public static &lt;T&gt; int count(Class&lt;T&gt; entityClass)
      {
          CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
          Root&lt;T&gt; rt = cq.from(entityClass);
          cq.select(getEntityManager().getCriteriaBuilder().count(rt));
          Query q = getEntityManager().createQuery(cq);
  
          return ((Long) q.getSingleResult()).intValue();
      }
  }
  </code></pre>
  
  <p>This is my <code>DataSource</code> </p>
  
  <pre><code>package co.peewah.ems.utils;
  
  import java.beans.PropertyVetoException;
  import java.io.IOException;
  import java.sql.Connection;
  import java.sql.SQLException;
  
  import org.apache.commons.dbcp.BasicDataSource;
  
  import com.google.appengine.api.utils.SystemProperty;
  
  /**
   *
   * @author csacanam
   *
   */
  public class DataSource
  {
  
      private static DataSource datasource;
      private BasicDataSource ds;
  
      private DataSource() throws IOException, SQLException, PropertyVetoException
      {
          ds = new BasicDataSource();
  
  
          String mode = "";
  
          if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development)
          {
              mode = "dev.";
          }
  
          String user = System.getProperty("persistence." + mode + "db.user");
          String password = System.getProperty("persistence." + mode + "db.password");
          String address = System.getProperty("persistence." + mode + "db.url");
          String driver = System.getProperty("persistence." + mode + "db.driver");
  
          // Create and configure DBCP DataSource
          ds.setDriverClassName(driver);
          ds.setUrl(address);
          ds.setUsername(user);
          ds.setPassword(password);
  
          ds.setMinIdle(5);
          ds.setMaxIdle(20);
  
          ds.setMaxOpenPreparedStatements(180);
      }
  
      public static DataSource getInstance() throws IOException, SQLException, PropertyVetoException
      {
          if(datasource == null)
          {
              datasource = new DataSource();    
          }
  
          return datasource;
      }
  
      public Connection getConnection() throws SQLException
      {
          return this.ds.getConnection();
      }
  
  
  
  
  }
  </code></pre>