Example usage for javax.persistence EntityManager clear

List of usage examples for javax.persistence EntityManager clear

Introduction

In this page you can find the example usage for javax.persistence EntityManager clear.

Prototype

public void clear();

Source Link

Document

Clear the persistence context, causing all managed entities to become detached.

Usage

From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java

public synchronized EntityManagerFactory create(File database) throws MetadataException {
    EntityManagerFactory factory;//from w w  w.j  a v  a2s . c  o m
    String name = "metadata";
    Hashtable<String, String> persistProperties = new Hashtable<String, String>();
    persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    // This swallow all the output log from derby.
    System.setProperty("derby.stream.error.field",
            "com.nokia.helium.metadata.DerbyFactoryManagerCreator.DEV_NULL");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database.getAbsolutePath());
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
    if (database.exists()) {
        if (!checkDatabaseIntegrity(database)) {
            try {
                FileUtils.forceDelete(database);
            } catch (java.io.IOException iex) {
                throw new MetadataException("Failed deleting corrupted db: " + iex, iex);
            }
        } else {
            return Persistence.createEntityManagerFactory(name, persistProperties);
        }
    }
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database + ";create=true");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    factory = Persistence.createEntityManagerFactory(name, persistProperties);
    EntityManager entityManager = factory.createEntityManager();
    // Pushing default data into the current schema
    try {
        entityManager.getTransaction().begin();
        // Version of the schema is pushed.
        entityManager.persist(new Version());
        // Default set of severity is pushed.
        for (SeverityEnum.Severity severity : SeverityEnum.Severity.values()) {
            Severity pData = new Severity();
            pData.setSeverity(severity.toString());
            entityManager.persist(pData);
        }
        entityManager.getTransaction().commit();
    } finally {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
            entityManager.clear();
        }
        entityManager.close();
    }
    return factory;
}

From source file:org.compass.gps.device.jpa.indexer.DefaultJpaIndexEntitiesIndexer.java

public void performIndex(CompassSession session, IndexEntity[] entities) {
    for (IndexEntity indexEntity : entities) {
        EntityInformation entityInformation = (EntityInformation) indexEntity;
        if (jpaGpsDevice.isFilteredForIndex(entityInformation.getName())) {
            continue;
        }//  ww w . j  a v  a  2  s  .c om
        int fetchCount = jpaGpsDevice.getFetchCount();
        int current = 0;
        while (true) {
            if (!jpaGpsDevice.isRunning()) {
                return;
            }
            EntityManagerWrapper wrapper = jpaGpsDevice.getEntityManagerWrapper().newInstance();
            try {
                wrapper.open();
                EntityManager entityManager = wrapper.getEntityManager();
                if (log.isDebugEnabled()) {
                    log.debug(jpaGpsDevice.buildMessage("Indexing entities [" + entityInformation.getName()
                            + "] range [" + current + "-" + (current + fetchCount) + "] using query ["
                            + entityInformation.getQueryProvider() + "]"));
                }
                Query query = entityInformation.getQueryProvider().createQuery(entityManager,
                        entityInformation);
                query.setFirstResult(current);
                query.setMaxResults(fetchCount);
                List results = query.getResultList();
                for (Object result : results) {
                    session.create(result);
                }
                session.evictAll();
                entityManager.clear();
                wrapper.close();
                if (results.size() < fetchCount) {
                    break;
                }
                current += fetchCount;
            } catch (Exception e) {
                log.error(jpaGpsDevice.buildMessage("Failed to index the database"), e);
                wrapper.closeOnError();
                if (!(e instanceof JpaGpsDeviceException)) {
                    throw new JpaGpsDeviceException(jpaGpsDevice.buildMessage("Failed to index the database"),
                            e);
                }
                throw (JpaGpsDeviceException) e;
            }
        }
    }
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

@Override
public <T extends BaseEntity> void batchInsert(List<T> entities, int batchSize) {
    Validate.isTrue(entities != null && !entities.isEmpty() && batchSize > 1, "Invalid inputs!!");
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {//from   w  w  w. j  a v a 2 s .com
        em.getTransaction().begin();
        for (int index = 0; index < entities.size(); index++) {
            if (index > 0 && index % batchSize == 0) {
                em.getTransaction().commit();
                em.getTransaction().begin();
                em.clear();
            }
            em.persist(entities.get(index));
        }
        em.getTransaction().commit();
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:in.bookmylab.jpa.JpaDAO.java

public User saveUser(User user, boolean savePassword) {
    EntityManager em = emf.createEntityManager();
    try {//w  w  w .j  a  v  a 2s. com
        user.password = Utils.hashPassword(user.password);
        em.getTransaction().begin();
        if (user.userId == null) {
            grantDefaultRoleToUser(em, user);
            em.persist(user);
        } else {
            user = em.merge(user);
            if (savePassword) {
                Query q = em.createNamedQuery("User.setPassword");
                q.setParameter("password", user.password);
                q.setParameter("userId", user.userId);
                q.executeUpdate();
            }
        }
        em.getTransaction().commit();
    } finally {
        em.clear();
        em.close();
    }
    return user;
}

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;/*from w w w. j a v a  2  s.  c o m*/
    EntityManager em = null;
    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:br.usp.ime.lapessc.xflow2.core.VCSMiner.java

private void buildAndStoreCommit(VCSMiningProject miningProject, CommitDTO commitDTO) {

    Commit commit = new Commit();

    commit.setAuthor(getAuthor(commitDTO));
    commit.setComment(commitDTO.getComment());
    commit.setDate(commitDTO.getDate());
    commit.setRevision(commitDTO.getRevision());
    commit.setVcsMiningProject(miningProject);
    commit.setEntryFiles(getEntryFiles(commitDTO));
    commit.setEntryFolders(getEntryFolders(commitDTO));

    try {// w  w  w . j  a  va  2s .  c  o  m
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.persist(commit);
        manager.getTransaction().commit();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }

    fixOperationType(commit);

    //Fix parent folder for folders
    for (Folder folder : commit.getEntryFolders()) {
        fixFolder(folder, commit);
    }

    //Fix parent folder for files
    setParentFolders(commit);

    setDeletedOnForFileArtifacts(commit);
    setDeletedOnForFolders(commit);

    if (miningProject.getMiningSettings().isCodeDownloadEnabled()) {
        setLocMeasures(commit);
    }

    try {
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.flush();
        manager.getTransaction().commit();
        manager.clear();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }
}

From source file:com.impetus.client.couchdb.crud.CouchDBClientTest.java

@Test
@PerfTest(invocations = 10)//  w  w w .ja  v a2  s  .c om
public void testCRUDWithBatch() {
    Map<String, String> batchProperty = new HashMap<String, String>(1);
    batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, "5");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(_PU, batchProperty);
    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    Assert.assertEquals(5, ((Batcher) client).getBatchSize());

    final String originalName = "vivek";

    for (int i = 0; i < 9; i++) {
        PersonCouchDB object = new PersonCouchDB();
        object.setAge(32);
        object.setPersonId(ROW_KEY + i);
        object.setPersonName(originalName);
        em.persist(object);

        if (i >= 5) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNull(result);
        } else if (i > 0 && i % 4 == 0) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNotNull(result);
            Assert.assertEquals(result.getPersonId(), object.getPersonId());
            Assert.assertEquals(result.getAge(), object.getAge());
            Assert.assertEquals(result.getPersonName(), object.getPersonName());
        }
    }
    em.flush();
    em.clear();
    em.close();
    em = null;
}

From source file:org.dragoneronca.nlp.wol.graph_building.WolGraphBuilder.java

@Override
public void run() {
    if (executed) {
        return;// ww  w . ja va  2  s. c o  m
    }
    executed = true;
    LOG.info("Start");

    WolDomainContext domainContext = WolDomainContext.getInstance();
    EntityManager entityManager = domainContext.getEntityManager();

    Set<SenseSet> senseSetsBunch;
    Iterator<SenseSet> senseSetIterator = domainContext.senseSetIterator(SENSESETS_BUNCH_SIZE);
    while (!(senseSetsBunch = getBunchOfSenseSets(senseSetIterator, SENSESETS_BUNCH_SIZE)).isEmpty()) {

        RangedSenseScanner rangedSenseScanner = new RangedSenseScanner(SENSES_BUNCH_SIZE);
        while (rangedSenseScanner.hasNext()) {
            RangedSenseIteratorFactory rangedSenseIteratorFactory = rangedSenseScanner.next();
            RangedSenseScanner.AlphabeticRange alphabeticRange = rangedSenseIteratorFactory.getRange();

            entityManager.getTransaction().begin();

            SenseSetProcessor processor = null;
            switch (graphType) {
            case SIMILARITY_BASED:
                processor = new SimilarityBasedProcessor(rangedSenseIteratorFactory, alphabeticRange);
                break;
            }

            int processed = 0;
            long startTime = System.currentTimeMillis();
            for (SenseSet senseSet : senseSetsBunch) {
                processor.processSenseSet(senseSet);
                processed++;

                long endTime = System.currentTimeMillis();
                if (endTime - startTime > DELTA_TIME) {
                    LOG.info("SenseSet processed: " + processed);
                    startTime = endTime;
                }

                if (processed % COMMIT_RATE == 0) {
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                }
            }
            entityManager.getTransaction().commit();
            Runtime.getRuntime().gc();
        }
        entityManager.clear();
        Runtime.getRuntime().gc();
    }
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Removes alert history and current alerts for the specified alert defintiion
 * ID. This will invoke {@link EntityManager#clear()} when completed since the
 * JPQL statement will remove entries without going through the EM.
 *
 * @param definitionId//from w ww  .ja  v  a  2 s.c o m
 *          the ID of the definition to remove.
 */
@Transactional
public void removeByDefinitionId(long definitionId) {
    EntityManager entityManager = m_entityManagerProvider.get();
    TypedQuery<AlertCurrentEntity> currentQuery = entityManager
            .createNamedQuery("AlertCurrentEntity.removeByDefinitionId", AlertCurrentEntity.class);

    currentQuery.setParameter("definitionId", definitionId);
    currentQuery.executeUpdate();

    TypedQuery<AlertHistoryEntity> historyQuery = entityManager
            .createNamedQuery("AlertHistoryEntity.removeByDefinitionId", AlertHistoryEntity.class);

    historyQuery.setParameter("definitionId", definitionId);
    historyQuery.executeUpdate();

    entityManager.clear();

    // if caching is enabled, invalidate the cache to force the latest values
    // back from the DB
    if (m_configuration.isAlertCacheEnabled()) {
        m_currentAlertCache.invalidateAll();
    }
}

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

/**
 * @see org.opencms.db.I_CmsProjectDriver#log(org.opencms.db.CmsDbContext, java.util.List)
 *//*from  www  .java2s .  c  o m*/
public void log(CmsDbContext dbc, List<CmsLogEntry> logEntries) throws CmsDbSqlException {

    try {

        EntityManager em = m_sqlManager.getEntityManager(dbc);
        em.getTransaction().commit();
        CmsDAOLog daoLog;
        for (CmsLogEntry logEntry : logEntries) {
            em.getTransaction().begin();
            daoLog = new CmsDAOLog();
            daoLog.setUserId(logEntry.getUserId().toString());
            daoLog.setLogDate(logEntry.getDate());
            daoLog.setStructureId(
                    logEntry.getStructureId() == null ? null : logEntry.getStructureId().toString());
            daoLog.setLogType(logEntry.getType().getId());
            daoLog.setLogData(CmsStringUtil.arrayAsString(logEntry.getData(), "|"));
            em.persist(daoLog);
            // here commits on each record, 
            // because there may be a duplicate records
            // and just ignore them
            try {
                if ((em.getTransaction() != null) && em.getTransaction().isActive()) {
                    em.getTransaction().commit();
                }
            } catch (RuntimeException e) {
                if ((em.getTransaction() != null) && em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
            } finally {
                em.clear();
            }
        }
        em.getTransaction().begin();
    } catch (PersistenceException e) {
        throw new CmsDbSqlException(Messages.get().container(Messages.ERR_GENERIC_SQL_1, ""), e);
    }
}