title: Getting HibernateException : The internal connection pool has reached its maximum size and no connection is currently available
body: <p>I am getting org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available! I believe the problem is due to incorrect session handling. Can anyone suggest the correct way? </p>
  
  <p>This is my Service class.</p>
  
  <pre><code>@Service
  public class DataService {
  
      @Autowired
      private SessionFactory sessionFactory;
  
      public User createUser(User newUser) {
          Session session = sessionFactory.openSession();
          session.beginTransaction();
          session.save(newUser);
          session.getTransaction().commit();
          session.close();
          return newUser;
      }
  
      public User findUser(UUID userId) {
          Session session = sessionFactory.openSession();
          session.beginTransaction();
          try {
              return session.get(User.class, userId);
          } finally {
              session.close();
          }
      }
  }
  </code></pre>
  
  <p>Below is my Hibernate Configuration. I think my configuration is correct. My Session instantiation and closing in-service class is wrong.</p>
  
  <pre><code>&lt;!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt;
  &lt;hibernate-configuration&gt;
      &lt;session-factory&gt;
          &lt;property name="connection.driver_class"&gt;com.mysql.cj.jdbc.Driver&lt;/property&gt;
          &lt;property name="connection.url"&gt;jdbc:mysql://localhost:3306/rest_database?useSSL=false&lt;/property&gt;
          &lt;property name="connection.username"&gt;admin&lt;/property&gt;
          &lt;property name="connection.password"&gt;admin&lt;/property&gt;
  
          &lt;property name="connection.pool_size"&gt;1&lt;/property&gt;
          &lt;property name="dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/property&gt;
          &lt;property name="show_sql"&gt;true&lt;/property&gt;
          &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt;
          &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;
          &lt;property name="hibernate.dbcp.initialSize"&gt;5&lt;/property&gt;
          &lt;property name="hibernate.dbcp.maxTotal"&gt;20&lt;/property&gt;
          &lt;property name="hibernate.dbcp.maxIdle"&gt;10&lt;/property&gt;
          &lt;property name="hibernate.dbcp.minIdle"&gt;5&lt;/property&gt;
          &lt;property name="hibernate.dbcp.maxWaitMillis"&gt;-1&lt;/property&gt;
  
          &lt;mapping class="com.in.models.User" /&gt;
      &lt;/session-factory&gt;
  
  &lt;/hibernate-configuration&gt;
  </code></pre>