title: JPA connection closed with EntityManager
body: <p>Please excuse the possible improper formatting of this post as I have never posted here before.  I have a Spring MVC web service running that calls into several DAO's that use JPA/hibernate to interact with a SQL Server database.  The connection to the database seems to get closed after the web service has been running for a while.</p>
  
  <p>An example of one of the DAO classes is the following:</p>
  
  <pre><code>@Repository
  public class OceanClientDaoImpl {
  
  // Create entity manager objects that will talk to the database
  private EntityManagerFactory entityManagerFactory;
  
  /**
   * Load all clients in the database. Return as ClientLight objects.
   * 
   * @return List of ClientLight objects.
   */
  public List&lt;Client&gt; loadClients() 
  {
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      entityManager.getTransaction().begin();
      List&lt;?&gt; clients = 
              entityManager.createNativeQuery("select id, clientname, industry, logo, slug from client", 
                      Client.class).getResultList();
      entityManager.getTransaction().commit();
      entityManager.close();
      return Client.getCheckedList(clients);
  }
  }
  </code></pre>
  
  <p>The entityManagerFactory is injected via spring in the following way:</p>
  
  <pre><code>&lt;bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"&gt;
      &lt;property name="driverClassName"     value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /&gt;
      &lt;property name="url" value="url" /&gt;
      &lt;property name="username" value="user" /&gt;
      &lt;property name="password" value="pw" /&gt;
  &lt;/bean&gt;
  
  &lt;bean
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      id="entityManagerFactory"&gt;
      &lt;property name="dataSource" ref="dataSource" /&gt;
  &lt;/bean&gt;
  
  &lt;context:component-scan base-package="com.theocean.dao"&gt;
      &lt;context:include-filter type="annotation"
          expression="org.springframework.stereotype.Repository" /&gt;
  &lt;/context:component-scan&gt;
  
  &lt;bean class="org.springframework.orm.jpa.JpaTransactionManager"
      id="transactionManager"&gt;
      &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="oceanClientDaoImpl" class="com.theocean.dao.OceanClientDaoImpl"&gt;
      &lt;property name="entityManagerFactory" ref="entityManagerFactory"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>This all works fine when I first bring up the application.  The application server is Tomcat.  But, after the application is running for a while, requests to the server start receiving this error:</p>
  
  <pre><code>&gt; SEVERE: Servlet.service() for servlet [spring] in context with path [/OceanWebService] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: JDBC begin failed: ] with root cause
  com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed.
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
      at com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4844)
      at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6154)
      at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6106)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection$1ConnectionCommand.doExecute(SQLServerConnection.java:1756)
      at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectionCommand(SQLServerConnection.java:1761)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.setAutoCommit(SQLServerConnection.java:1901)
      at sun.reflect.GeneratedMethodAccessor32.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
      at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:99)
      at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:58)
      at com.sun.proxy.$Proxy32.setAutoCommit(Unknown Source)
      at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:87)
      at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
      at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:60)
      at com.theocean.dao.OceanClientDaoImpl.loadClients(OceanClientDaoImpl.java:52)
      at com.theocean.service.ExperienceClientService.loadClientsLight(ExperienceClientService.java:30)
      at com.theocean.web.ExperienceController.loadClientsLight(ExperienceController.java:30)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
      at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
      at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
      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:669)
      at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)
  SEVERE: Servlet.service() for servlet [spring] in context with path [/OceanWebService]     threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: JDBC begin failed: ] with root cause
  com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed.
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
      at com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4844)
      at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6154)
      at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6106)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection$1ConnectionCommand.doExecute(SQLServerConnection.java:1756)
      at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectionCommand(SQLServerConnection.java:1761)
      at com.microsoft.sqlserver.jdbc.SQLServerConnection.setAutoCommit(SQLServerConnection.java:1901)
      at sun.reflect.GeneratedMethodAccessor32.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
      at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:99)
      at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:58)
      at com.sun.proxy.$Proxy32.setAutoCommit(Unknown Source)
      at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:87)
      at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
      at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:60)
      at com.theocean.dao.OceanClientDaoImpl.loadClients(OceanClientDaoImpl.java:52)
      at com.theocean.service.ExperienceClientService.loadClientsLight(ExperienceClientService.java:30)
      at com.theocean.web.ExperienceController.loadClientsLight(ExperienceController.java:30)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
      at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
      at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
      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:669)
      at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)
  </code></pre>
  
  <p>So, the connection is being closed.  Obviously something is wrong with the implementation whether it be the injection method or the method for handling errors, etc.  So, the question is - What is the proper way to do this?  How can I avoid the connection closed error?  Thanks much in advance.</p>