title: java.lang.IllegalStateException: EntityManager is closed
body: <p>I'm building a JAR file, deploying to JBoss 4.2.3.GA (can't help it), with Hibernate 4.1.5.SP1 with validator 4.3.0.Final.  The database is MySQL 5.5.  I'm having problems executing basic selects using a RESOURCE_LOCAL EntityManager.  I have  </p>
  
  <pre><code>        for (final Order order : results) { 
          ...                 
                      try { 
                          session = (Session)em.getDelegate();
                          state = findStateByAbbrev(stateAbbrev, session);
                      } catch (HibernateException e) {
                          e.printStackTrace(System.err);
                          LOG.error(e.getMessage(), e);
                      } finally {
                          em.close();
                      }   // try 
  
          }   // for
  
  private State findStateByAbbrev(final String abbrev, final Session session) {
      State ret = null;
      final Criteria crit = session.createCriteria(State.class).add(Restrictions.eq("abbrev", abbrev));
      final List&lt;State&gt; results = crit.list();
      if (results != null &amp;&amp; results.size() &gt; 0) {
          ret = results.get(0);
      }   // if
      return ret;
  }
  </code></pre>
  
  <p>Here's my META-INF/persistence.xml file …</p>
  
  <pre><code>&lt;persistence&gt;
      &lt;persistence-unit name="didoclientunit" transaction-type="RESOURCE_LOCAL"&gt;
          &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
          &lt;non-jta-data-source&gt;java:/MySqlDS&lt;/non-jta-data-source&gt;
          &lt;properties&gt;
              &lt;property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml" /&gt;
              &lt;property name="hibernate.validator.apply_to_ddl"&gt;false&lt;/property&gt;
              &lt;property name="hibernate.validator.autoregister_listeners"&gt;false&lt;/property&gt;
              &lt;property name="hibernate.transaction.manager_lookup_class" value=" org/hibernate/transaction/TransactionManagerLookup"/&gt; --&gt;
          &lt;/properties&gt;
      &lt;/persistence-unit&gt;
  &lt;/persistence&gt;
  </code></pre>
  
  <p>and here's the hibernate config file …</p>
  
  <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
  &lt;!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
  
  &lt;hibernate-configuration&gt;
      &lt;session-factory&gt;
          &lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;
          &lt;property name="show_sql"&gt;true&lt;/property&gt;
          &lt;property name="dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
  
          &lt;!-- Enable Hibernate's automatic session context management --&gt;
          &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt;
  
          &lt;mapping class="com.parentco.fdr.myproject.model.UserRole" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.Organization" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.Product" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.State" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.Country" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.AccessCode" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.Contract" /&gt;
          &lt;mapping class="com.parentco.fdr.myproject.model.TrainingLink" /&gt;
  
      &lt;/session-factory&gt;
  &lt;/hibernate-configuration&gt;
  </code></pre>
  
  <p>During the first loop, everything's fine, but the second time around, I get this exception.  If I don't close the EntityManager, I get transaction timeouts after 5 minutes (the length of my JBoss transaction timeout), so I'm confused as to how I should be coding this.  I want to continue to use Hibernate's Criteria API.</p>
  
  <pre><code>java.lang.IllegalStateException: EntityManager is closed
      at org.hibernate.ejb.EntityManagerImpl.close(EntityManagerImpl.java:58)
      at org.mainco.subco.dido.service.OrderServiceImpl.getPDOrders(OrderServiceImpl.java:153)
      at org.mainco.subco.dido.quartz.ProcessPDWorker.work(ProcessPDWorker.java:24)
      at org.mainco.subco.dido.quartz.ProcessPDJob.execute(ProcessPDJob.java:42)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:112)
      at org.jboss.ejb3.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:166)
      at org.jboss.ejb3.interceptor.EJB3InterceptorsInterceptor.invoke(EJB3InterceptorsInterceptor.java:63)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.entity.TransactionScopedEntityManagerInterceptor.invoke(TransactionScopedEntityManagerInterceptor.java:54)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:47)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:126)
      at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:195)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:62)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.mdb.MessagingContainer.localInvoke(MessagingContainer.java:249)
      at org.jboss.ejb3.mdb.inflow.MessageInflowLocalProxy.delivery(MessageInflowLocalProxy.java:268)
      at org.jboss.ejb3.mdb.inflow.MessageInflowLocalProxy.invoke(MessageInflowLocalProxy.java:138)
      at $Proxy83.execute(Unknown Source)
      at org.jboss.resource.adapter.quartz.inflow.QuartzJob.execute(QuartzJob.java:57)
      at org.quartz.core.JobRunShell.run(JobRunShell.java:203)
      at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:520)
  </code></pre>
  
  <p>Thanks, - Dave</p>
  
  <p><b>Edit:</b> Trying Tiago's response works until my code has run longer than the setting in the $JBOSS_HOME/server/default//conf/jboss-service.xml</p>
  
  <p>
     
        400</p>
  
  <p>Exactly 400 seconds after I start, I get the exception below</p>
  
  <pre><code>21:41:40,025 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.BasicAction_58] - Abort of action id -3f57ff9c:ca5e:502dadac:34 invoked while multiple threads active within it.
  21:41:40,026 WARN  [arjLoggerI18N] [com.arjuna.ats.arjuna.coordinator.CheckedAction_2] - CheckedAction::check - atomic action -3f57ff9c:ca5e:502dadac:34 aborting with 1 threads active!
  21:41:40,410 WARN  [JDBCExceptionReporter] SQL Error: 0, SQLState: null
  21:41:40,410 ERROR [JDBCExceptionReporter] Transaction is not active: tx=TransactionImple &lt; ac, BasicAction: -3f57ff9c:ca5e:502dadac:34 status: ActionStatus.ABORTED &gt;; - nested throwable: (javax.resource.ResourceException: Transaction is not active: tx=TransactionImple &lt; ac, BasicAction: -3f57ff9c:ca5e:502dadac:34 status: ActionStatus.ABORTED &gt;)
  21:41:40,412 ERROR [STDERR] org.hibernate.exception.GenericJDBCException: Cannot open connection
      at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
      at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
      at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
      at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:139)
      at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1547)
      at org.hibernate.loader.Loader.doQuery(Loader.java:673)
      at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
      at org.hibernate.loader.Loader.doList(Loader.java:2220)
      at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
      at org.hibernate.loader.Loader.list(Loader.java:2099)
      at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:94)
      at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569)
      at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
      at org.mainco.subco.dido.service.OrderServiceImpl.findStateByAbbrev(OrderServiceImpl.java:450)
      at org.mainco.subco.dido.service.OrderServiceImpl.getPDOrders(OrderServiceImpl.java:144)
      at org.mainco.subco.dido.quartz.ProcessPDWorker.work(ProcessPDWorker.java:24)
      at org.mainco.subco.dido.quartz.ProcessPDJob.execute(ProcessPDJob.java:42)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:112)
      at org.jboss.ejb3.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:166)
      at org.jboss.ejb3.interceptor.EJB3InterceptorsInterceptor.invoke(EJB3InterceptorsInterceptor.java:63)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.entity.TransactionScopedEntityManagerInterceptor.invoke(TransactionScopedEntityManagerInterceptor.java:54)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:47)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:126)
      at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:195)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:62)
      at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
      at org.jboss.ejb3.mdb.MessagingContainer.localInvoke(MessagingContainer.java:249)
      at org.jboss.ejb3.mdb.inflow.MessageInflowLocalProxy.delivery(MessageInflowLocalProxy.java:268)
      at org.jboss.ejb3.mdb.inflow.MessageInflowLocalProxy.invoke(MessageInflowLocalProxy.java:138)
      at $Proxy83.execute(Unknown Source)
      at org.jboss.resource.adapter.quartz.inflow.QuartzJob.execute(QuartzJob.java:57)
      at org.quartz.core.JobRunShell.run(JobRunShell.java:203)
      at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:520)
  </code></pre>