Skip to content

Instantly share code, notes, and snippets.

@ferrao
Last active October 9, 2017 21:27
Show Gist options
  • Save ferrao/a03a2517d207135ad6e39082f5ff714d to your computer and use it in GitHub Desktop.
Save ferrao/a03a2517d207135ad6e39082f5ff714d to your computer and use it in GitHub Desktop.
JPA EntityManager util class using thread local to assure thread-safety
public class EntityManagerHelper {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
static {
emf = Persistence.createEntityManagerFactory("BookStoreUnit");
threadLocal = new ThreadLocal<EntityManager>();
}
public static EntityManager getEntityManager() {
EntityManager em = threadLocal.get();
if (em == null) {
em = emf.createEntityManager();
threadLocal.set(em);
}
return em;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
if (em != null) {
em.close();
threadLocal.set(null);
}
}
public static void closeEntityManagerFactory() {
emf.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment