code: public final <T> T executeInTransaction(final Runnable<T> runnable, final boolean clearAfterCommit)
              throws Exception {
          T result;
  
          try {
              entityManager.getTransaction().begin();
              result = runnable.run(entityManager);
              entityManager.flush();
              entityManager.getTransaction().commit();
  
              if (clearAfterCommit) {
                  entityManager.clear();
              }
          } finally {
              if (entityManager.getTransaction().isActive()) {
                  entityManager.getTransaction().rollback();
              }
          }
  
          return result;
      }
docs: Encapsulates execution of runnable.run() in transactions.
  
  @param <T>
  result type of runnable.run()
  @param runnable
  algorithm to execute
  @param clearAfterCommit
  <tt>true</tt> triggers entityManager.clear() after transaction
  commit
  @return return value of runnable.run()
  @throws Exception
  execution failed