Last active
April 26, 2017 15:05
-
-
Save dilnei/a7b756be6e1090515aaa to your computer and use it in GitHub Desktop.
JPAUtil (ThreadLocal<EntityManager>)
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
package br.com.app.util; | |
import javax.persistence.EntityManager; | |
import javax.persistence.EntityManagerFactory; | |
import javax.persistence.Persistence; | |
public class JPAUtil { | |
private static final String PERSISTENCE_UNIT = "appUnitPU"; | |
private static ThreadLocal<EntityManager> threadLocal; | |
private static EntityManagerFactory factory; | |
/** | |
* Bloco estatico, inicializa na instancia da classe, carregando a unidade | |
* de persistencia. | |
*/ | |
static { | |
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); | |
threadLocal = new ThreadLocal<EntityManager>(); | |
} | |
/** | |
* Metodo que retorna uma EntityManager. | |
* | |
* @return | |
*/ | |
public static EntityManager getEntityManager() { | |
if (threadLocal.get() == null) { | |
threadLocal.set(factory.createEntityManager()); | |
} | |
return threadLocal.get(); | |
} | |
/** | |
* Responsavel por fechar a EntityManager. | |
*/ | |
public static void closeEntityManager() { | |
EntityManager em = threadLocal.get(); | |
if (em != null) { | |
threadLocal.remove(); | |
em.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Classe utilitária JPAUtil (cria e encerra a EntityManager)
Utilizo esta classe em aplicações web-profile (action-based) e aplicações standalone, note que ele sempre procura por uma instância já criada na ThreadLocal, caso não exista ele gera uma nova em.