title: How to tell if a transaction is active in a Java EE 6 interceptor?
body: <p>I am planning to write an interceptor for an EJB that will do basically the following:</p>
  
  <pre><code>@AroundInvoke
  public Object setContext(InvocationContext ctx) throws Exception {
      em.createQuery("... set something [database specific] ...").getSingleResult();
      try {
          return ctx.proceed();
      } finally {
          em.flush();
          em.createQuery("... unset something [database specific] ...").getSingleResult();
      }
  }
  </code></pre>
  
  <p>The problem is that em.flush() throws an exception if it is applied to a method annotated with @TransactionAttribute(NOT_SUPPORTED) or @TransactionAttribute(SUPPORTS) (i.e. read-only methods), while it works fine with methods using the default @TransactionAttribute(REQUIRED) (i.e. methods that change the database).</p>
  
  <p><strong>Is there a way to tell whether a transaction is active</strong> in order to avoid the call to em.flush() when there is no transaction currently running, or must I create two interceptors, one with em.flush() and one without it?</p>
  
  <p>I cannot inject a UserTransaction since the bean uses container-managed transactions. EntityManager's (em) transaction methods only work with resource_local transactions, not with JTA transactions. I need the em.flush() call to be sure that the <em>unset</em> query is the last thing that runs.</p>
  
  <p>As bonus question, does anyone knows if what I am trying to do is some kind of bad practice? I know that the interceptor runs in the same context as the bean, so it will be safe to share things via the database session, but I must be <em>really careful</em> to unset everything on exit because connections are pooled in the container.</p>