Example usage for javax.persistence EntityManagerFactory createEntityManager

List of usage examples for javax.persistence EntityManagerFactory createEntityManager

Introduction

In this page you can find the example usage for javax.persistence EntityManagerFactory createEntityManager.

Prototype

public EntityManager createEntityManager();

Source Link

Document

Create a new application-managed EntityManager.

Usage

From source file:org.rhq.server.metrics.migrator.DataMigratorRunner.java

private void run() throws Exception {
    log.debug("Creating Entity Manager");
    EntityManagerFactory entityManagerFactory = this.createEntityManagerFactory();
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    log.debug("Done creating Entity Manager");

    log.debug("Creating Cassandra session");
    Session cassandraSession = this.createCassandraSession();
    log.debug("Done creating Cassandra session");

    DatabaseType databaseType = DatabaseType.Postgres;
    if (configuration.get(sqlServerTypeOption) != null) {
        databaseType = (DatabaseType) configuration.get(sqlServerTypeOption);
    }/*  ww  w. j a va 2s .  co m*/

    DataMigrator migrator = new DataMigrator(entityManager, cassandraSession, databaseType,
            tryParseBoolean(configuration.get(experimentalExportOption), false));

    if (!(Boolean) configuration.get(deleteOnlyOption)) {
        if ((Boolean) configuration.get(deleteDataOption)) {
            migrator.deleteAllDataAtEndOfMigration();
        } else {
            migrator.preserveData();
        }

        migrator.runRawDataMigration(!(Boolean) configuration.get(disableRawOption));
        migrator.run1HAggregateDataMigration(!(Boolean) configuration.get(disable1HOption));
        migrator.run6HAggregateDataMigration(!(Boolean) configuration.get(disable6HOption));
        migrator.run1DAggregateDataMigration(!(Boolean) configuration.get(disable1DOption));

        System.out.println("Estimation process - starting\n");
        long estimate = migrator.estimate();
        System.out.println("The migration process will take approximately: "
                + TimeUnit.MILLISECONDS.toMinutes(estimate) + " minutes (or " + estimate + " milliseconds)\n");
        System.out.println("Estimation process - ended\n\n");

        if (!(Boolean) configuration.get(estimateOnlyOption)) {
            System.out.println("Migration process - starting\n");
            long startTime = System.currentTimeMillis();
            migrator.migrateData();
            long duration = System.currentTimeMillis() - startTime;
            System.out.println("The migration process took: " + TimeUnit.MILLISECONDS.toMinutes(duration)
                    + " minutes (or " + duration + " milliseconds)\n");
            System.out.println("Migration process - ended\n");
        }
    } else {
        migrator.deleteAllDataAtEndOfMigration();
        migrator.runRawDataMigration(false);
        migrator.run1HAggregateDataMigration(false);
        migrator.run6HAggregateDataMigration(false);
        migrator.run1DAggregateDataMigration(false);

        System.out.println("Estimation process - starting\n");
        long estimate = migrator.estimate();
        System.out.println("The deletion of old data will take approximately: "
                + TimeUnit.MILLISECONDS.toMinutes(estimate) + " minutes (or " + estimate + " milliseconds)\n");
        System.out.println("Estimation process - ended\n\n");

        if (!(Boolean) configuration.get(estimateOnlyOption)) {
            migrator.runRawDataMigration(true);
            migrator.run1HAggregateDataMigration(true);
            migrator.run6HAggregateDataMigration(true);
            migrator.run1DAggregateDataMigration(true);

            System.out.println("Old data deletion process - starting\n");
            long startTime = System.currentTimeMillis();
            migrator.deleteOldData();
            long duration = System.currentTimeMillis() - startTime;
            System.out.println("The deletion process took: " + TimeUnit.MILLISECONDS.toMinutes(duration)
                    + " minutes (or " + duration + " milliseconds)\n");
            System.out.println("Old data deletion process - ended\n");
        }
    }

    this.closeCassandraSession(cassandraSession);
    this.closeEntityManagerFactory(entityManagerFactory);
}

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

private void checkSQLRefresh(Object obj, ClassLoader urlk, String punit) {
    ClassLoader oldKL = Thread.currentThread().getContextClassLoader();
    EntityManagerFactory emf = null;
    EntityManager em = null;/*  w  w w . ja  v a 2 s  .c om*/
    try {
        Thread.currentThread().setContextClassLoader(urlk);

        HashMap props = new HashMap();
        props.put("hibernate.hbm2ddl.auto", "create-drop");
        emf = Persistence.createEntityManagerFactory(punit, props);

        em = emf.createEntityManager();

        checkJPARefresh(obj, ((UIdAble) obj).getDyEntryId(), em);

    } finally {
        Thread.currentThread().setContextClassLoader(oldKL);
        if (em != null && em.isOpen()) {
            em.clear();
            em.close();
        }
        if (emf != null && emf.isOpen()) {
            emf.close();
        }
    }

}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Returns a list of all {@link org.globus.wsrf.Resource}s, which are managed by an EntityManager, corresponding to
 * the given EntityManagerFactory and//  w  ww . j a  v a  2 s  .  co  m
 * which are managed by the {@code GNDMPersistentServiceHome} {@link de.zib.gndms.infra.system.GNDMSystemDirectory#getHome(Class)}    
 *
 * @param emg the factory to create the EntityManager, used for the {@code list all} query
 * @param clazz the class, whose corresponding GNDMPersistentServiceHome will be used for the query.(See {@link de.zib.gndms.infra.system.GNDMSystemDirectory#homes})
 * @param <M> the model type
 * @return  a list of all {@code Resources}, corresponding to a specific EntityManager and GNDMPersistentServiceHome.
 */
public final @NotNull <M extends GridResource> List<String> listAllResources(
        final @NotNull EntityManagerFactory emg, final @NotNull Class<M> clazz) {
    final EntityManager manager = emg.createEntityManager();
    List<String> retList = null;
    try {
        try {
            manager.getTransaction().begin();
            retList = listAllResources(getInstanceDir().getHome(clazz), manager);
            manager.getTransaction().commit();
        } finally {
            if (manager.getTransaction().isActive())
                manager.getTransaction().rollback();
        }
    } finally {
        if (manager.isOpen())
            manager.close();
    }
    return retList;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends EntityBaseStandard> T find(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;/*from  www .j  a  va  2s .co  m*/

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        returnValue = (T) em.find(classObj, id);
    } catch (Exception e) {
        // logger.error("Errore su find di controller : " + e.getMessage() +
        // " " + e.getCause() != null ? e.getCause().getMessage() : "");
        ExceptionLogger.logExceptionWithCause(logger, e);
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * Usato specialmente per aggiornare dopo un salvataggio. Nel caso delle
 * applicazioni web usiamo em che si chiude dopo la request quindi gli
 * oggetti non si aggiornano in automatico dopo il salvataggio.
 * //from w ww.ja v a2s  .  c o m
 * @param <T>
 * @param classObj
 * @param id
 * @return
 * @throws Exception
 */
public <T extends EntityBaseStandard> T findAndRefresh(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        returnValue = (T) em.find(classObj, id);

        if (returnValue != null) {
            // if (lazyCloseEM) {
            em.refresh(returnValue);
            // }
        }

    } catch (Exception e) {
        // logger.error("Errore su find di controller : " + e.getMessage() +
        // " " + e.getCause() != null ? e.getCause().getMessage() : "");
        ExceptionLogger.logExceptionWithCause(logger, e);
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * //  www.j  a  v  a2 s  .  c  o  m
 * Restituisce loggetto relativo specificando classe ed id
 * 
 * @param classObj
 * @param id
 * @return EntityBase
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> T find2(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Calcolo l'oggetto */
        returnValue = (T) em.find(classObj, id);
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public int getItemCount(Class classObj) throws Exception {
    int returnValue = 0;

    EntityManagerFactory emf = null;
    EntityManager em = null;//from w w w . j av  a  2s.  c o  m
    Query q = null;
    StringBuffer hsqlQuery = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        hsqlQuery = new StringBuffer();
        hsqlQuery.append("select count(*) from ");
        hsqlQuery.append(classObj.getCanonicalName());
        hsqlQuery.append(" as o");
        q = em.createQuery(hsqlQuery.toString());
        returnValue = ((Long) q.getSingleResult()).intValue();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
        q = null;
        hsqlQuery = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * /*ww w  . j a v  a 2 s  .co  m*/
 * Metodo che restituisce il numero di elementi dato un certo tipo
 * 
 * @param classObj
 * @return
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> int getItemCount3(Class<T> classObj) throws Exception {
    int returnValue = 0;

    StringBuffer hsqlQuery = null;
    EntityManagerFactory emf = null;
    EntityManager em = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Creo la query */
        hsqlQuery = new StringBuffer();
        hsqlQuery.append("select count(*) from "); // hsqlQuery.append("select count(o) from ");
        // ho cambiato
        hsqlQuery.append(classObj.getCanonicalName());
        hsqlQuery.append(" as o");
        q = em.createQuery(hsqlQuery.toString());

        /* Istanzio il valore di retutn */
        returnValue = ((Long) q.getSingleResult()).intValue();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        hsqlQuery = null;
        em = null;
        q = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends EntityBaseStandard> List<String> getDisinctStringValues(Class<T> classObj, String property)
        throws Exception {
    List<String> returnValue = null;

    StringBuffer hsqlQuery = null;
    EntityManagerFactory emf = null;
    EntityManager em = null;/*w w  w  .  j  a v  a 2  s  .co m*/
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Creo la query */
        hsqlQuery = new StringBuffer();
        hsqlQuery.append("select distinct(o." + property + ") from ");
        hsqlQuery.append(classObj.getCanonicalName());
        hsqlQuery.append(" as o");

        q = em.createQuery(hsqlQuery.toString());

        /* Istanzio il valore di retutn */
        returnValue = q.getResultList();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        hsqlQuery = null;
        em = null;
        q = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public int getItemCount(Class classObj, String query, Map<String, Object> map) throws Exception {
    int returnValue = 0;

    EntityManagerFactory emf = null;
    EntityManager em = null;/* w  w  w.  j a v  a  2s .c o m*/
    Query q = null;
    Iterator i = null;
    Map.Entry entry = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        q = em.createNamedQuery(query);

        if (map != null) {
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }
        returnValue = ((Long) q.getSingleResult()).intValue();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
        q = null;
        i = null;
        entry = null;
    }
    return returnValue;
}