Created
April 27, 2013 19:26
-
-
Save marcusschiesser/5474348 to your computer and use it in GitHub Desktop.
Utils class for doing transactions with Google App Engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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