Código PHP:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.exes.itecel.exception.PersistenceException;
public class PersistenceUtil {
private static ThreadLocal<EntityManager> threadLocal = new ThreadLocal<EntityManager>();
private static ThreadLocal<EntityTransaction> threadTx = new ThreadLocal<EntityTransaction>();
private static EntityManagerFactory emf = null;
public static EntityManager getEntityManager() throws PersistenceException{
try {
EntityManager em = threadLocal.get();
if (em == null || !em.isOpen()) {
if (emf == null) {
rebuildEntityManagerFactory();
}
em = (emf != null) ? emf.createEntityManager()
: null;
threadLocal.set(em);
}
return em;
} catch (RuntimeException e) {
throw new PersistenceException(e.getMessage(), e);
}
}
public static void rebuildEntityManagerFactory() throws PersistenceException{
try {
emf = Persistence.createEntityManagerFactory("Itecel");
} catch (RuntimeException e) {
throw new PersistenceException(e.getMessage(), e);
}
}
public static void closeEntityManager() throws PersistenceException{
try {
EntityManager em = threadLocal.get();
threadLocal.remove();
if (em != null) {
em.close();
}
} catch (RuntimeException e) {
throw new PersistenceException(e.getMessage(), e);
}
}
public static void beginTransaction() throws PersistenceException{
EntityTransaction tx = threadTx.get();
if (tx == null)
{
tx = getEntityManager().getTransaction();
threadTx.set(tx);
}
tx.begin();
}
public static void commitTransaction() throws PersistenceException{
try {
EntityTransaction tx = threadTx.get();
if ( tx != null && tx.isActive())
{
tx.commit();
}
threadTx.remove();
} catch (RuntimeException e) {
throw new PersistenceException(e.getMessage(), e);
}
}
public static void rollbackTransaction() throws PersistenceException{
try {
EntityTransaction tx = threadTx.get();
threadTx.remove();
if ( tx != null && tx.isActive() ) {
tx.rollback();
}
} catch (RuntimeException e) {
throw new PersistenceException(e.getMessage(), e);
}
}
}
yo uso esa clase que se encarga de obtener un entity manager, lo que permite esta clase es que si dos threads se conectan a tu aplicacion esta clase le asigan un entitymanager a cada thread y los almacena para eso uso la clase ThreadLocal, con esto controlo que la aplicacion pueda tener varios usuarios, talvez te pueda ser util
salu2