Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Utils class for doing transactions with Google App Engine
public final class TXUtils {
public static final Logger log = Logger.getLogger(TXUtils.class.getName());
public interface Transaction<T> {
T doit(EntityManager em);
}
private static final EntityManagerFactory emfInstance = Persistence
.createEntityManagerFactory("my-persistence-unit");
public static <T> T doTransaction(Transaction<T> transaction) {
EntityManager em = emfInstance.createEntityManager();
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
T retVal = transaction.doit(em);
tx.commit();
return retVal;
} catch (RuntimeException e) {
if (tx != null && tx.isActive())
tx.rollback();
log.log(Level.SEVERE, "error during transaction: "
+ transaction.getClass().getName(), e);
throw e;
} finally {
em.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.