Java examples for javax.persistence:EntityManager
Creates or returns current EntityManager with EntityTransaction started.
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class Main{ private static EntityManagerFactory entityManagerFactory; private static EntityManager entityManager; /**/* ww w . java 2 s. c o m*/ * Creates or returns current {@link EntityManager} with {@link EntityTransaction} started. * @return Current {@link EntityManager}. */ public static EntityManager currentEntityManager() { if (entityManager == null) { entityManager = entityManagerFactory(persistenceUnitName) .createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); } return entityManager; } /** * Creates or returns current {@link EntityManagerFactory}. * @param persistenceUnitName Persistence unit name form persistence.xml. * @return Current {@link EntityManagerFactory}. */ public static EntityManagerFactory entityManagerFactory( String persistenceUnitName) { if (entityManagerFactory == null) { JPAHelper.persistenceUnitName = persistenceUnitName; entityManagerFactory = Persistence .createEntityManagerFactory(JPAHelper.persistenceUnitName); } return entityManagerFactory; } }