@Override public <A> A tx(Function<EntityManager, A> transactional) { for (final EntityManager em : createEntityManager(emf)) { final EntityTransaction tx = em.getTransaction(); try { tx.begin(); emStore.set(Option.<Transactional>some(new Transactional() { @Override public <A> A tx(Function<EntityManager, A> transactional) { return transactional.apply(em); } })); A ret = transactional.apply(em); tx.commit(); return ret; } catch (Exception e) { if (tx.isActive()) { tx.rollback(); } // propagate exception return chuck(e); } finally { if (em.isOpen()) em.close(); emStore.remove(); } } return chuck(new IllegalStateException("EntityManager is already closed")); } };