Skip to content

Instantly share code, notes, and snippets.

@marcusschiesser
Created April 27, 2013 19:26
Show Gist options
  • Save marcusschiesser/5474348 to your computer and use it in GitHub Desktop.
Save marcusschiesser/5474348 to your computer and use it in GitHub Desktop.
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