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.chiralbehaviors.CoRE.kernel.Bootstrap.java

public static void main(String[] argv) throws Exception {
    if (argv.length != 2) {
        System.err.println("Usage: Bootstrap <jpa.properties> <output file>");
        System.exit(1);/*from w  w w  .j  a  v a2s  .  co m*/
    }
    Properties properties = new Properties();
    try (InputStream is = new FileInputStream(new File(argv[0]))) {
        properties.load(is);
    }

    EntityManagerFactory emf = Persistence.createEntityManagerFactory(WellKnownObject.CORE, properties);
    EntityManager em = emf.createEntityManager();
    Bootstrap bootstrap = new Bootstrap(em);
    bootstrap.clear();
    em.getTransaction().begin();
    bootstrap.bootstrap();
    em.getTransaction().commit();
    em.clear();
    bootstrap.serialize(argv[1]);
}

From source file:org.datahack.data.uploader.UploadTables.java

public static void main(String[] args) {

    EntityManager em = ParkingDBConnector.getEntityManager();

    try {/*w  w w  .j  a v a  2s.c  o m*/
        File output = File.createTempFile("WCC_ParkingStreets", "csv");
        output.deleteOnExit();
        String csvName = "WCC_ParkingStreets.csv";
        URL resource = UploadTables.class.getResource("/" + csvName);
        FileUtils.copyURLToFile(resource, output);
        CSVReader reader = new CSVReader(new FileReader(output.getPath()));

        //Headings
        String[] str = reader.readNext();
        em.getTransaction().begin();
        int row = 0;
        while (str != null) {
            row++;
            str = reader.readNext();
            if (str != null) {

                if (str.length == 4) {

                    ParkingStreet pS = new ParkingStreet();

                    try {

                        Integer id = Integer.parseInt(str[0]);
                        Integer usrn = Integer.parseInt(str[1]);
                        String streetName = str[2];
                        Integer parkingZoneKey = Integer.parseInt(str[3]);
                        pS.setId(id);
                        pS.setStreetName(streetName);
                        pS.setuSRN(usrn);

                        ParkingZone pZ = em.find(ParkingZone.class, parkingZoneKey);

                        if (pZ == null) {
                            pZ = new ParkingZone();
                            pZ.setId(parkingZoneKey);

                        }

                        pS.setParkingZone(pZ);
                        em.merge(pS);

                    } catch (NumberFormatException e) {
                        System.out.println("Failed to merge row " + row);
                    }

                    if (row % 1000 == 0) {
                        em.getTransaction().commit();
                        em.clear();
                        em.getTransaction().begin();
                    }

                }

            }

        }

        em.getTransaction().commit();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Uplad Bay data
    String csvName = "bay_table.csv";

    try {
        File output = File.createTempFile("bay_table", "csv");
        output.deleteOnExit();
        URL resource = UploadTables.class.getResource("/" + csvName);
        FileUtils.copyURLToFile(resource, output);
        CSVReader reader = new CSVReader(new FileReader(output.getPath()));

        //Headings
        String[] str = reader.readNext();
        em.getTransaction().begin();
        int row = 0;
        while (str != null) {
            row++;
            str = reader.readNext();
            if (str != null) {

                if (str.length == 5) {

                    Bay b = new Bay();
                    try {

                        Integer id = Integer.parseInt(str[0]);
                        Double lat = Double.parseDouble(str[1]);
                        Double lon = Double.parseDouble(str[2]);
                        Integer spaces = Integer.parseInt(str[3]);
                        Integer parkingStreetKey = Integer.parseInt(str[4]);

                        b.setId(id);
                        b.setLatitude(lat);
                        b.setLongitude(lon);
                        b.setTotalSpaces(spaces);

                        ParkingStreet find = em.find(ParkingStreet.class, parkingStreetKey);

                        if (find != null) {
                            ParkingZone pZ = find.getParkingZone();

                            if (pZ != null) {
                                Set<Bay> bays = pZ.getBays();

                                if (bays == null) {
                                    bays = new LinkedHashSet();
                                    pZ.setBays(bays);
                                }

                                bays.add(b);
                                b.setParkingZone(pZ);

                                //Calculate parking zone location as mean of lats and lons
                                Iterator<Bay> iterator = bays.iterator();
                                Integer numBays = bays.size();

                                Double latitude = 0.0;
                                Double longitude = 0.0;

                                while (iterator.hasNext()) {
                                    Bay next = iterator.next();
                                    latitude += next.getLatitude() / numBays;
                                    longitude += next.getLongitude() / numBays;

                                }

                                pZ.setLatitude(latitude);
                                pZ.setLongitude(longitude);
                            }

                            em.merge(pZ);

                            System.out.println("Bay added to zone");
                        }

                        em.merge(b);

                    } catch (NumberFormatException e) {
                        System.out.println("Failed to merge row " + row);
                    }

                    if (row % 1000 == 0) {
                        em.getTransaction().commit();
                        em.clear();
                        em.getTransaction().begin();
                    }

                }

            }

        }

        em.getTransaction().commit();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        File output = File.createTempFile("bay_event_table", "csv");
        output.deleteOnExit();
        csvName = "bay_event_table.csv";
        URL resource = UploadTables.class.getResource("/" + csvName);
        FileUtils.copyURLToFile(resource, output);
        CSVReader reader = new CSVReader(new FileReader(output.getPath()));

        //Headings
        String[] str = reader.readNext();
        em.getTransaction().begin();
        int row = 0;
        while (str != null) {
            row++;
            str = reader.readNext();
            if (str != null) {

                if (str.length == 4) {

                    BayEvent bE = new BayEvent();

                    try {

                        Integer id = Integer.parseInt(str[0]);
                        Integer bayId = Integer.parseInt(str[1]);
                        String eventTimeString = str[2];
                        Double estimatedSpaces = Double.parseDouble(str[3]);

                        bE.setId(id);

                        Bay find = em.find(Bay.class, bayId);
                        bE.setBay(find);

                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                        java.util.Date d;

                        d = df.parse(eventTimeString);

                        bE.setEventTime(d);

                        bE.setEstimatedSpaces(estimatedSpaces);

                        em.merge(bE);

                    } catch (NumberFormatException e) {
                        System.out.println("Failed to merge row " + row);
                    } catch (ParseException ex) {
                        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    if (row % 1000 == 0) {
                        em.getTransaction().commit();
                        em.clear();
                        em.getTransaction().begin();
                    }

                }

            }

        }

        em.getTransaction().commit();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:cn.guoyukun.spring.jpa.repository.hibernate.HibernateUtils.java

/**
 * 
 *
 * @param em
 */
public static void evictLevel1Cache(EntityManager em) {
    em.clear();
}

From source file:com.clustercontrol.jobmanagement.factory.FullJob.java

public static void initJobMstCache() {
    long startTime = System.currentTimeMillis();
    HashMap<String, Map<String, JobMstEntity>> jobMstCache = new HashMap<String, Map<String, JobMstEntity>>();
    JpaTransactionManager jtm = null;/*from  w w  w. jav a2s .co  m*/
    try {
        jtm = new JpaTransactionManager();
        EntityManager em = jtm.getEntityManager();
        em.clear();
        List<JobMstEntity> jobunits = ((HinemosEntityManager) em)
                .createNamedQuery("JobMstEntity.findByParentJobunitIdAndJobId", JobMstEntity.class,
                        ObjectPrivilegeMode.NONE)
                .setParameter("parentJobunitId", CreateJobSession.TOP_JOBUNIT_ID)
                .setParameter("parentJobId", CreateJobSession.TOP_JOB_ID).getResultList();

        for (JobMstEntity jobunit : jobunits) {
            String jobunitId = jobunit.getId().getJobunitId();
            List<JobMstEntity> jobs = ((HinemosEntityManager) em)
                    .createNamedQuery("JobMstEntity.findByJobunitId", JobMstEntity.class,
                            ObjectPrivilegeMode.NONE)
                    .setParameter("jobunitId", jobunitId).getResultList();
            Map<String, JobMstEntity> jobunitMap = new HashMap<String, JobMstEntity>();
            for (JobMstEntity job : jobs) {
                String jobId = job.getId().getJobId();
                jobunitMap.put(jobId, job);
            }
            jobMstCache.put(jobunitId, jobunitMap);
        }
        m_log.info("init jobMstCache " + (System.currentTimeMillis() - startTime) + "ms. size="
                + jobMstCache.size());
        for (Map.Entry<String, Map<String, JobMstEntity>> entry : jobMstCache.entrySet()) {
            m_log.info("jobMstCache key(jobunitId)=" + entry.getKey() + " size=" + entry.getValue().size());
        }

        storeJobMstCache(jobMstCache);
    } finally {
        if (jtm != null) {
            jtm.close();
        }
    }
}

From source file:org.fornax.cartridges.sculptor.framework.web.jpa.ConversationDomainObjectJpaRepositoryImpl.java

public <T> void clear() {
    getJpaTemplate().execute(new JpaCallback<T>() {
        public T doInJpa(EntityManager em) throws PersistenceException {
            em.clear();
            return null;
        }/*from  w w w .  j a v  a2s  .  c om*/

    });
}

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

/**
 * @see org.apache.commons.pool.BasePoolableObjectFactory#passivateObject(java.lang.Object)
 *///from   w w w  .j a va  2s  . c  om
@Override
public void passivateObject(Object obj) {

    EntityManager em = (EntityManager) obj;
    em.clear();
}

From source file:com.workplacesystems.queuj.process.seam.SeamTransaction.java

@Observer("processTransactionComplete")
public void transactionComplete(TransactionContext context) {
    if (context.obsolete)
        return;/*  w  ww  . j a v a 2s. c  o m*/
    context.obsolete = true;

    log.debug("Rolling back transaction " + context.transactionId);
    FilterableArrayList<ProcessServer> processServers = new FilterableArrayList<ProcessServer>();
    for (ProcessWrapper process : context.processes) {
        ProcessServer ps = process.getContainingServer();
        if (!processServers.contains(ps))
            processServers.add(ps);
    }
    for (ProcessServer ps : processServers)
        ((ProcessImplServer) ps).rollback();

    EntityManager em = (EntityManager) Component.getInstance("entityManager");
    em.clear();
}

From source file:org.dragoneronca.nlp.wol.domain.WolEntityIterator.java

@SuppressWarnings("unchecked")
private boolean retrieveResults() {
    if (ended) {//from   w w  w . j  ava2s  .  c  o m
        return false;
    } else if (!results.isEmpty()) {
        return true;
    }

    WolDomainContext domainContext = WolDomainContext.getInstance();
    EntityManager entityManager = domainContext.getEntityManager();
    if (clear) {
        entityManager.clear();
    }
    TypedQuery<T> q = entityManager.createNamedQuery(name, tClass);

    if (parameters != null) {
        int i = 1;
        for (Object parameter : parameters) {
            q.setParameter(i++, parameter);
        }
    }
    q.setFirstResult(offset).setMaxResults(max);

    long startQueryTime = System.currentTimeMillis();
    if (logEnabled) {
        LOG.info("Starting query: " + name + "\t\tType: " + tClass.getSimpleName());
    }

    Runtime.getRuntime().gc();
    List<T> resultList = q.getResultList();

    if (!resultList.isEmpty()) {
        results.addAll(resultList);
        offset += results.size();

        long endQueryTime = System.currentTimeMillis();
        if (logEnabled) {
            LOG.info("Retrieved " + results.size() + " results in " + ((endQueryTime - startQueryTime) / 1000)
                    + " sec.");
        }

        return true;
    } else {
        ended = true;
        return false;
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletEntityDao.java

@Override
@PortalTransactionalRequiresNew/*from ww w.  j av a 2  s .  c  o m*/
public boolean portletEntityExists(IPortletEntityId portletEntityId) {
    Validate.notNull(portletEntityId, "portletEntityId can not be null");

    final EntityManager entityManager = this.getEntityManager();
    entityManager.clear();

    final long internalPortletEntityId = getNativePortletEntityId(portletEntityId);
    final PortletEntityImpl portletEntity = entityManager.find(PortletEntityImpl.class,
            internalPortletEntityId);
    return portletEntity != null;
}

From source file:com.workplacesystems.queuj.process.seam.SeamTransaction.java

@Observer("processTransactionSuccess")
public void transactionSuccess(final TransactionContext context) {
    if (context.obsolete)
        return;//from w ww .j  a  v  a 2  s.  co m
    context.obsolete = true;

    log.debug("Commiting transaction " + context.transactionId);
    FilterableArrayList<ProcessServer> processServers = new FilterableArrayList<ProcessServer>();
    for (ProcessWrapper process : context.processes) {
        ProcessServer ps = process.getContainingServer();
        if (!processServers.contains(ps))
            processServers.add(ps);
    }
    for (ProcessServer ps : processServers)
        ((ProcessImplServer) ps).commit();

    for (Callback<Void> commitCallback : context.commitCallbacks) {
        try {
            commitCallback.action();
        } catch (Exception e) {
            new QueujException(e);
        }
    }

    final Callback<Void> async = QueujFactory.getAsyncCallback(new Callback<Void>() {
        @Override
        protected void doAction() {
            for (final ProcessWrapper process : context.startProcesses) {
                if (process.rescheduleRequired(false))
                    process.interruptRunner();
                else
                    process.start();
            }

            for (final ProcessWrapper process : context.processes) {
                process.callListeners();
            }
        }
    });

    Thread thread = new Thread(new Runnable() {
        public void run() {
            async.action();
        }
    });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException ie) {
    }

    EntityManager em = (EntityManager) Component.getInstance("entityManager");
    em.clear();
}