Last active
October 9, 2017 21:27
-
-
Save ferrao/a03a2517d207135ad6e39082f5ff714d to your computer and use it in GitHub Desktop.
JPA EntityManager util class using thread local to assure thread-safety
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 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