Example usage for javax.persistence EntityManager createQuery

List of usage examples for javax.persistence EntityManager createQuery

Introduction

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

Prototype

public Query createQuery(CriteriaDelete deleteQuery);

Source Link

Document

Create an instance of Query for executing a criteria delete query.

Usage

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void getAllInstalledBunPrinted() {
    logger.info("================= getAll() ==================START");

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    List<InstalledBun> lb = entityManager.createQuery("select p from InstalledBun p").getResultList();
    for (Iterator iterator = lb.iterator(); iterator.hasNext();) {
        InstalledBun iBun = (InstalledBun) iterator.next();
        logger.info("=== InstalledBun found: " + iBun.getName() + ", Id: " + iBun.getId() + ", Uuid: "
                + iBun.getUuid() + ", RepoUrl: " + iBun.getRepoUrl() + ", InstalledVersion: "
                + iBun.getInstalledVersion() + ", PackageURL: " + iBun.getPackageURL() + ", PackageLocalPath: "
                + iBun.getPackageLocalPath() + ", Status: " + iBun.getStatus());

    }//from  w ww .  jav a  2  s .  c  o m

    logger.info("================= getAll() ==================END");
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void getAllUsersPrinted() {
    logger.info("================= getAllUsers() ==================START");

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    List<BakerUser> lb = entityManager.createQuery("select p from BakerUser p").getResultList();
    for (Iterator iterator = lb.iterator(); iterator.hasNext();) {
        BakerUser bu = (BakerUser) iterator.next();
        logger.info("   ======> BakerUser found: " + bu.getName() + ", Id: " + bu.getId() + ", Id: "
                + bu.getOrganization() + ", username: " + bu.getUsername());

        List<Product> products = bu.getProducts();
        for (Product prod : products) {
            logger.info("   ======> bunMetadata found: " + prod.getName() + ", Id: " + prod.getId()
                    + ", getUuid: " + prod.getUuid() + ", getName: " + prod.getName());
        }/*w w w  . j  a  va  2  s. c  om*/

    }
    logger.info("================= getAll() ==================END");
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void getAllSubscribedResourcesPrinted() {
    logger.info("================= getSubscribedResource() ==================START");

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    List<SubscribedResource> lb = entityManager.createQuery("select p from SubscribedResource p")
            .getResultList();/*from w  w  w  .j av  a  2  s  .  c o  m*/
    for (Iterator iterator = lb.iterator(); iterator.hasNext();) {
        SubscribedResource sm = (SubscribedResource) iterator.next();
        logger.info("   ======> SubscribedResource found: " + sm.getURL() + ", Id: " + sm.getId());

    }
}

From source file:com.jada.admin.site.SiteLoader.java

public void loadShippingRegion() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from ShippingRegion where siteId = :siteId order by shippingRegionId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingRegion master = (ShippingRegion) iterator.next();
        ShippingRegion shippingRegion = new ShippingRegion();
        Set<Country> countries = shippingRegion.getCountries();
        Set<State> states = shippingRegion.getStates();
        PropertyUtils.copyProperties(shippingRegion, master);
        shippingRegion.setSite(site);/*from  w  ww  . jav a 2 s  .c  o  m*/
        shippingRegion.setShippingRegionId(null);
        shippingRegion.setRecUpdateBy(userId);
        shippingRegion.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        shippingRegion.setRecCreateBy(userId);
        shippingRegion.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        shippingRegion.setCountries(countries);
        shippingRegion.setStates(states);
        shippingRegion.setZipCodes(null);
        shippingRegion.setShippingMethodRegions(null);
        shippingRegion.setShippingMethodRegionTypes(null);
        Iterator<?> it = null;
        if (master.getCountries() != null) {
            it = master.getCountries().iterator();
            while (it.hasNext()) {
                Country mc = (Country) it.next();
                Country country = CountryDAO.loadByCountryName(site.getSiteId(), mc.getCountryName());
                shippingRegion.getCountries().add(country);
            }
        }
        if (master.getStates() != null) {
            it = master.getStates().iterator();
            while (it.hasNext()) {
                State mc = (State) it.next();
                State state = StateDAO.loadByStateName(site.getSiteId(), mc.getStateName());
                shippingRegion.getStates().add(state);
            }
        }
        shippingRegions.add(shippingRegion);
        em.persist(shippingRegion);
    }
}

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

@Override
public <T extends BaseEntity> Long count(Class<T> entity) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {/* w w  w.ja v  a2  s. co m*/
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Long> cq = cb.createQuery(Long.class);
        return em.createQuery(cq.select(cb.count(cq.from(entity)))).getSingleResult();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes a newsdrilldown from the db./*from  www.  j av  a  2s  .com*/
 *
 * @param entity The newsdrilldown to delete
 */
public void delete(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString());
        query.setParameter("fs_id", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            News art = (News) query.getSingleResult();
            // delete file from filesystem
            URL url = new URL(art.getUrl());
            File file = new File(webpath + url.getPath());
            if (file.exists()) {
                // Try acquiring the lock without blocking. This method returns
                // null or throws an exception if the file is already locked.
                try {
                    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
                    // Try to lock the file
                    FileLock lock = channel.tryLock();
                    // Delete the file
                    file.delete();
                    // Release the lock
                    lock.release();
                    lock.channel().close();
                } catch (OverlappingFileLockException e) {
                    logger.info("File is already locked in this thread or virtual machine");
                } catch (MalformedURLException e) {
                    logger.info("wrong url", e);
                }
            }
            // remove article from content repository

            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.jada.admin.site.SiteLoader.java

public void loadShippingMethod() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from ShippingMethod where siteId = :siteId order by shippingMethodId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingMethod master = (ShippingMethod) iterator.next();
        ShippingMethod shippingMethod = new ShippingMethod();
        shippingMethod.setSite(site);//from   w w  w  .j  a v  a  2s  . c  o m
        shippingMethod.setSeqNum(master.getSeqNum());
        shippingMethod.setPublished(master.getPublished());
        shippingMethod.setRecUpdateBy(userId);
        shippingMethod.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        shippingMethod.setRecCreateBy(userId);
        shippingMethod.setRecCreateDatetime(new Date(System.currentTimeMillis()));

        for (ShippingMethodLanguage language : master.getShippingMethodLanguages()) {
            ShippingMethodLanguage shippingMethodLanguage = new ShippingMethodLanguage();
            shippingMethodLanguage.setShippingMethodName(language.getShippingMethodName());
            shippingMethodLanguage.setRecUpdateBy(userId);
            shippingMethodLanguage.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
            shippingMethodLanguage.setRecCreateBy(userId);
            shippingMethodLanguage.setRecCreateDatetime(new Date(System.currentTimeMillis()));
            em.persist(shippingMethodLanguage);
            if (language.getShippingMethodLangId()
                    .equals(master.getShippingMethodLanguage().getShippingMethodLangId())) {
                shippingMethod.setShippingMethodLanguage(shippingMethodLanguage);
            }
            shippingMethod.getShippingMethodLanguages().add(shippingMethodLanguage);
        }

        if (master.getShippingMethodRegions() != null) {
            Iterator<?> it = master.getShippingMethodRegions().iterator();
            while (it.hasNext()) {
                ShippingMethodRegion m_shippingMethodRegion = (ShippingMethodRegion) it.next();
                ShippingMethodRegion shippingMethodRegion = new ShippingMethodRegion();
                shippingMethodRegion.setPublished(m_shippingMethodRegion.getPublished());
                shippingMethodRegion.setRecUpdateBy(userId);
                shippingMethodRegion.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
                shippingMethodRegion.setRecCreateBy(userId);
                shippingMethodRegion.setRecCreateDatetime(new Date(System.currentTimeMillis()));
                shippingMethodRegion.setShippingMethod(shippingMethod);
                ShippingRegion shippingRegion = getShippingRegion(
                        m_shippingMethodRegion.getShippingRegion().getShippingRegionName());
                shippingMethodRegion.setShippingRegion(shippingRegion);

                if (m_shippingMethodRegion.getShippingMethodRegionTypes() != null) {
                    Iterator<?> it1 = m_shippingMethodRegion.getShippingMethodRegionTypes().iterator();
                    while (it1.hasNext()) {
                        ShippingMethodRegionType m_shippingMethodRegionType = (ShippingMethodRegionType) it1
                                .next();
                        ShippingMethodRegionType shippingMethodRegionType = new ShippingMethodRegionType();
                        shippingMethodRegionType.setPublished(m_shippingMethodRegionType.getPublished());
                        shippingMethodRegionType.setRecUpdateBy(userId);
                        shippingMethodRegionType.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
                        shippingMethodRegionType.setRecCreateBy(userId);
                        shippingMethodRegionType.setRecCreateDatetime(new Date(System.currentTimeMillis()));
                        shippingMethodRegionType.setShippingRegion(shippingRegion);
                        shippingMethodRegionType.setShippingMethod(shippingMethod);
                        shippingMethodRegionType.setShippingType(getShippingType(
                                m_shippingMethodRegionType.getShippingType().getShippingTypeName()));

                        ShippingRate m_shippingRate = m_shippingMethodRegionType.getShippingRate();
                        ShippingRate shippingRate = new ShippingRate();
                        PropertyUtils.copyProperties(shippingRate, m_shippingRate);
                        shippingRate.setPublished(m_shippingRate.getPublished());
                        shippingRate.setRecUpdateBy(userId);
                        shippingRate.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
                        shippingRate.setRecCreateBy(userId);
                        shippingRate.setRecCreateDatetime(new Date(System.currentTimeMillis()));
                        shippingMethodRegionType.setShippingRate(shippingRate);

                        em.persist(shippingRate);
                        em.persist(shippingMethodRegionType);
                        shippingMethodRegion.getShippingMethodRegionTypes().add(shippingMethodRegionType);
                    }
                }

                shippingMethod.getShippingMethodRegions().add(shippingMethodRegion);
            }
        }
        em.persist(shippingMethod);
    }
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public List<ApplicationMetadata> readAppsMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;/* w  ww.  j a v a 2  s  .  c o m*/

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager.createQuery(
                "SELECT a FROM ApplicationMetadata a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM ApplicationMetadata a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:streaming.StreamingTest.java

public void verifNbGenreEgal6() {
    EntityManager em = Persistence.createEntityManagerFactory("StreamingPU").createEntityManager();
    //        Collection<Genre> genre = em.createQuery("SELECT g FROM Genre g").getResultList();
    //        Assert.assertEquals(6, genre.size());

    //2eme mthode : 
    Long nbGenre = (Long) em.createQuery("SELECT COUNT(g) FROM Genre g").getSingleResult();
    Assert.assertTrue(nbGenre == 6L);//  w ww.j ava 2  s.  c  o  m

}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes every item older than the creationTime of the UXBEntity.
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *///from w w w.  j  a v  a 2s .  c  om
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        // Remove old newsdrilldown
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM news x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                News art = (News) obj;
                em.remove(art);
            }
        }

        // Remove old newsCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM category x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsCategory art = (NewsCategory) obj;
                em.remove(art);
            }
        }

        // Remove old newsMetaCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM metaCategory x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsMetaCategory art = (NewsMetaCategory) obj;
                em.remove(art);
            }
        }

        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        logger.error("Failure while deleting from the database", e);
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}