title: MySQLNonTransientConnectionException: Too many connections
body: <p>My Spring-MVC application sometimes crashes when navigating around the site, the error message I've gotten from the logs are found below. I have absolutely no idea of what is causing this and would be very thankful for any tips that'll lead me in the right direction. </p>
  
  <pre><code>    SEVERE: Servlet.service() for servlet HS threw exception
  com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
      at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
      at com.mysql.jdbc.Util.getInstance(Util.java:382)
      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
      at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
      at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1116)
      at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2338)
      at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2371)
      at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2163)
      at com.mysql.jdbc.ConnectionImpl.&lt;init&gt;(ConnectionImpl.java:794)
      at com.mysql.jdbc.JDBC4Connection.&lt;init&gt;(JDBC4Connection.java:47)
      at sun.reflect.GeneratedConstructorAccessor56.newInstance(Unknown Source)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
      at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
      at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:378)
      at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
      at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
      at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
      at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
      at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
      at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
      at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
      at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)
      at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
      at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
      at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
      at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1577)
      at org.hibernate.loader.Loader.doQuery(Loader.java:696)
      at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
      at org.hibernate.loader.Loader.doList(Loader.java:2232)
      at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
      at org.hibernate.loader.Loader.list(Loader.java:2124)
      at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
      at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
      at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
      at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149)
      at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
      at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:921)
      at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
      at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
      at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
      at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
      at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:904)
      at se.hs.daos.UserDAOImpl.findByName(UserDAOImpl.java:42)
      at se.hs.controllers.LoginController.checkPassword(LoginController.java:20)
      at se.hs.pagecontrollers.LoginPageController.submitForm(LoginPageController.java:26)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:616)
      at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
      at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
      at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
      at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
      at java.lang.Thread.run(Thread.java:636)
  </code></pre>
  
  <p>What my UserDaoImpl looks like:</p>
  
  <pre><code>package se.hs.daos;
  
  import java.util.List;
  
  import org.hibernate.SessionFactory;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.support.ClassPathXmlApplicationContext;
  import org.springframework.orm.hibernate3.HibernateTemplate;
  import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
  
  import se.hs.models.User;
  
  public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
  
      private ApplicationContext context = new ClassPathXmlApplicationContext(
              "classpath*:applicationContext.xml");
      private SessionFactory sessionFactory = (SessionFactory) context
              .getBean("mySessionFactory");
      private HibernateTemplate hibernateTemplate = new HibernateTemplate(
              sessionFactory, true);
  
      public void saveUser(User user) {
          hibernateTemplate.save(user);
      }
  
      public User getUserById(Integer id) {
  
          User userFromDB = hibernateTemplate.get(User.class, id);
          return userFromDB;
      }
  
      public void removeUser(User user) {
          hibernateTemplate.delete(user);
      }
  
      public User findByName(String name) {
  
          String query = "SELECT u.userId FROM User u WHERE u.userName='" + name
                  + "'";
  
          @SuppressWarnings("unchecked")
          List&lt;Integer&gt; list = hibernateTemplate.find(query);
  
          User userFromDB = null;
  
          if (list.size() &gt; 0) {
              userFromDB = getUserById(list.get(0));
          }
  
          return userFromDB;
      }
  
  }
  </code></pre>
  
  <p>UPDATE: </p>
  
  <pre><code>    exception
  
  org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: Cannot release connection; uncategorized SQLException for SQL [???]; SQL state [null]; error code [0]; Already closed.; nested exception is java.sql.SQLException: Already closed.
      org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
      org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  root cause
  
  org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: Cannot release connection; uncategorized SQLException for SQL [???]; SQL state [null]; error code [0]; Already closed.; nested exception is java.sql.SQLException: Already closed.
      org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
      org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
      org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
      org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
      org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
      org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
      org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
      org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683)
      se.hsr.daos.InfoTextDAOImpl.saveInfoText(InfoTextDAOImpl.java:26)
      se.hsr.controllers.InfoTextController.saveInfoText(InfoTextController.java:31)
      se.hsr.pagecontrollers.InfoTextPageController.submitForm(InfoTextPageController.java:35)
      sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      java.lang.reflect.Method.invoke(Method.java:616)
      org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
      org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
      org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
      org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
      org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
      org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
      org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  root cause
  
  java.sql.SQLException: Already closed.
      org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:114)
      org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.close(PoolingDataSource.java:191)
      org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.closeConnection(LocalDataSourceConnectionProvider.java:95)
      org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:474)
      org.hibernate.jdbc.ConnectionManager.aggressiveRelease(ConnectionManager.java:429)
      org.hibernate.jdbc.ConnectionManager.afterStatement(ConnectionManager.java:304)
      org.hibernate.jdbc.AbstractBatcher.closePreparedStatement(AbstractBatcher.java:572)
      org.hibernate.jdbc.AbstractBatcher.closeStatement(AbstractBatcher.java:291)
      org.hibernate.id.insert.AbstractReturningDelegate.releaseStatement(AbstractReturningDelegate.java:82)
      org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:60)
      org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2176)
      org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2656)
      org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
      org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
      org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
      org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
      org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
      org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
      org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
      org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
      org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
      org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
      org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:563)
      org.hibernate.impl.SessionImpl.save(SessionImpl.java:551)
      org.hibernate.impl.SessionImpl.save(SessionImpl.java:547)
      org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:686)
      org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1)
      org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
      org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
      org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683)
      se.hsr.daos.InfoTextDAOImpl.saveInfoText(InfoTextDAOImpl.java:26)
      se.hsr.controllers.InfoTextController.saveInfoText(InfoTextController.java:31)
      se.hsr.pagecontrollers.InfoTextPageController.submitForm(InfoTextPageController.java:35)
      sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      java.lang.reflect.Method.invoke(Method.java:616)
      org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
      org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
      org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
      org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
      org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
      org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
      org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  </code></pre>