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:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

public static EntityManager getRUbioSeqEntityMananger() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    return em;/* ww  w  .j a  va2  s  .  c  om*/
}

From source file:org.isatools.isatab.commandline.PersistenceShellCommand.java

/**
 * TODO: this is a patch used until we are able to make the auto-indexing upon load feature working
 * It is called after persistence.// ww  w .java 2  s . co  m
 *
 * @param store               must contain the studies that have to be reindexed (with proper accession).
 * @param hibernateProperties - The hibernate properties indicating DB properties and Index location/Strategy,
 *                            and so forth.
 */
public static void reindexStudies(BIIObjectStore store, Properties hibernateProperties) {
    // Need to initialize this here, otherwise above config will fail
    log = Logger.getLogger(PersistenceShellCommand.class);

    hibernateProperties.setProperty("hibernate.search.indexing_strategy", "event");
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
    hibernateProperties.setProperty("hbm2ddl.drop", "false");

    EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("BIIEntityManager", hibernateProperties);
    EntityManager entityManager1 = emf1.createEntityManager();

    StudyDAO studyDAO = DaoFactory.getInstance(entityManager1).getStudyDAO();
    FullTextEntityManager fullTxtEm = Search.getFullTextEntityManager(entityManager1);
    EntityTransaction tnx = entityManager1.getTransaction();

    tnx.begin();
    for (Study study : store.valuesOfType(Study.class)) {
        Study dbStudy = studyDAO.getByAcc(study.getAcc());
        if (dbStudy != null) {
            out.println("Indexing Study #" + dbStudy.getAcc());
            fullTxtEm.index(dbStudy);
            log.info("Indexing of Study # " + dbStudy.getAcc() + " is complete!");
        }

    }
    log.info("Commiting & closing Entity Manager.");
    tnx.commit();
    entityManager1.close();
}

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

public static void main2(String[] args) throws Exception {
    BasicConfigurator.configure();//from w w w  .  ja  va  2 s .c om
    Logger.getRootLogger().setLevel(Level.INFO);
    Logger.getLogger("org.rhq").setLevel(Level.DEBUG);
    EntityManagerFactory entityManagerFactory = null;
    EntityManager entityManager = null;
    ExistingDataBulkExportSource source = null;
    try {
        entityManagerFactory = createEntityManager();
        entityManager = entityManagerFactory.createEntityManager();
        source = new ExistingPostgresDataBulkExportSource(entityManager,
                "SELECT  schedule_id, time_stamp, value, minvalue, maxvalue FROM RHQ_MEASUREMENT_DATA_NUM_1D");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        source.initialize();
        int rowIndex = 0;
        int maxResults = 30000;
        for (;;) {
            List<Object[]> existingData = source.getData(rowIndex, maxResults);
            if (existingData.size() < maxResults) {
                break;
            } else {
                rowIndex += maxResults;
            }
        }
        stopWatch.stop();
        System.out.println("Execution: " + stopWatch);
    } finally {
        if (source != null) {
            source.close();
        }
        if (entityManager != null) {
            entityManager.close();
        }
        if (entityManagerFactory != null) {
            entityManagerFactory.close();
        }
    }
}

From source file:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

/**
 * This method is responsible for the initializacion of the BD, that is:
 * - Creating the default RUbioSeqConfiguration.
 * - Creating the default users.// w w  w.j a v a 2  s. c o m
 * - Creating a datastore pointing to "/" for the admin user.
 * 
 * This method also plays a key role in the deployment of the application 
 * since it prints the message "[DBInitializer] DB initialized." which is
 * triggered by the launch-rubioseq-gui.sh in order to know that the app. is
 * deployed and launch a browser.
 * 
 * @author hlfernandez
 */
static void initDatabase() {
    System.out.println("[DBInitializer] Initializing DB ...");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        /*
         * Store Global Configuration
         */
        if (em.createQuery("SELECT u FROM RUbioSeqConfiguration u").getResultList().size() == 0) {
            RUbioSeqConfiguration config = new RUbioSeqConfiguration();
            config.setRubioseqCommand("/opt/RUbioSeq3.7/RUbioSeq.pl");
            config.setPrivateDatastoresRootDirectory("/path/to/private/datastores/root");
            config.setCreatePrivateDatastoresOnUserRegistration(false);

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(config);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Users
         */
        if (em.createQuery("SELECT u FROM User u").getResultList().size() == 0) {
            User user = new User();
            user.setUsername("rubiosequser");
            user.setPassword(DigestUtils.md5Hex("rubioseqpass"));
            user.setAdmin(false);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }

            user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5Hex("admin"));
            user.setAdmin(true);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Datastores
         */
        boolean createDefaultAdminDatastore = true;
        List<User> adminUsers = getAdminUsers(em);
        @SuppressWarnings("unchecked")
        List<DataStore> datastores = (List<DataStore>) em.createQuery("SELECT d FROM DataStore d")
                .getResultList();
        for (User adminUser : adminUsers) {
            if (datastores.size() == 0) {
                createDefaultAdminDatastore = true;
            } else {
                for (DataStore d : datastores) {
                    if (d.getUser() != null && d.getUser().equals(adminUser) && d.getPath().equals("/")) {
                        createDefaultAdminDatastore = false;
                    }
                }
            }
            if (createDefaultAdminDatastore) {
                DataStore adminDS = new DataStore();
                adminDS.setUser(adminUser);
                adminDS.setPath("/");
                adminDS.setMode(DataStoreMode.Private);
                adminDS.setType(DataStoreType.Input_Output);
                adminDS.setName(adminUser.getUsername() + "_default");

                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.persist(adminDS);
                    tx.commit();
                } finally {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                }
            }
        }
    } finally {
        em.close();
    }

    System.out.println("[DBInitializer] DB initialized.");
}

From source file:com.brienwheeler.lib.db.DbTestUtils.java

public static <T> T doInHibernateSession(ApplicationContext applicationContext, Callable<T> work) {
    EntityManagerFactory entityManagerFactory = applicationContext
            .getBean("com.brienwheeler.lib.db.appEntityManagerFactory", EntityManagerFactory.class);

    EntityManagerHolder entityManagerHolder = (EntityManagerHolder) TransactionSynchronizationManager
            .getResource(entityManagerFactory);

    boolean created = entityManagerHolder == null;
    if (created) {
        entityManagerHolder = new EntityManagerHolder(entityManagerFactory.createEntityManager());
        TransactionSynchronizationManager.bindResource(entityManagerFactory, entityManagerHolder);
    }/*from www. jav  a  2s. c o m*/

    try {
        return work.call();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (created)
            TransactionSynchronizationManager.unbindResource(entityManagerFactory);
    }
}

From source file:org.kuali.rice.krad.data.jpa.JpaMetadataProviderTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    metadataProvider = new EclipseLinkJpaMetadataProviderImpl();
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("krad-data-unit-test");
    metadataProvider.setEntityManager(entityManagerFactory.createEntityManager());
}

From source file:org.opencms.db.jpa.CmsSqlManager.java

/**
 * Create EntityManager instance for given unit name. If factory
 * for this unit is not already created it creates one.<p>
 * // w ww .j a v  a 2  s  . co  m
 * @param unitName - the unit name in the persistence.xml file
 * @return EntityManager instance for given unit name
 */
public static EntityManager createEntityManager(String unitName) {

    EntityManager em = null;
    EntityManagerFactory factory = getFactory(unitName);

    if (factory != null) {
        em = factory.createEntityManager();
    }
    return em;
}

From source file:com.redhat.rhtracking.config.JPAConfig.java

@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.createEntityManager();
}

From source file:org.cloudfoundry.reconfiguration.spring.AbstractJpaBasedCloudServiceBeanFactoryPostProcessorTest.java

protected final void assertConfiguration(EntityManagerFactory factory, String dialect) {
    EntityManager entityManager = factory.createEntityManager();

    Object session = getSession(entityManager);
    Object sessionFactory = getSessionFactory(session);
    Object actual = getDialect(sessionFactory);

    assertEquals(dialect, actual.toString());
}

From source file:dao.UsuarioDao.java

public List<Usuario> consultarTodosUsuarios() {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("LoginUsersPU");
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();/*  w w w  .  ja  v  a  2 s  .c  o m*/
    Query q = em.createNamedQuery("Usuario.findAll");
    List<Usuario> todosUsuarios = q.getResultList();
    return todosUsuarios;
}