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:de.ks.idnadrev.information.view.InformationOverviewDS.java

private List<InformationPreviewItem> getResults(String name, List<String> tagNames, Category category,
        EntityManager em, CriteriaBuilder builder, Class<? extends Information<?>> clazz) {
    CriteriaQuery<InformationPreviewItem> query = builder.createQuery(InformationPreviewItem.class);
    Root<? extends Information<?>> root = query.from(clazz);

    ArrayList<Predicate> filters = new ArrayList<>();
    if (!name.isEmpty()) {
        filters.add(builder.like(builder.lower(root.<String>get(KEY_NAME)), name));
    }/*from  w ww  .j  a v a  2 s.  c  o m*/
    if (!tagNames.isEmpty()) {
        List<Tag> tags = getTags(tagNames, em);
        SetJoin<TextInfo, Tag> tagJoin = root.joinSet(KEY_TAGS);
        filters.add(tagJoin.in(tags));
    }
    if (category != null) {
        filters.add(builder.equal(root.get(KEY_CATEGORY), category));
    }
    query.distinct(true);

    query.where(filters.toArray(new Predicate[filters.size()]));
    query.select(
            builder.construct(InformationPreviewItem.class, root.get(KEY_NAME), root.get(KEY_CREATIONTIME)));
    List<InformationPreviewItem> resultList = em.createQuery(query).getResultList();
    return resultList;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

protected String[] getOrganisationLayers(EntityManager em, Integer[] orgIds, String version, boolean isAdmin)
        throws Exception {
    List<SpLayerSummary> spLayers = null;
    if (!isAdmin) {
        String query = "select distinct new " + "nl.b3p.ogc.utils.SpLayerSummary(l, 'true',sp) "
                + "from Organization o " + "join o.wfsLayers l " + "join l.wfsServiceProvider sp "
                + "where o.id in (:orgIds) " + "and sp.allowed = true";
        if (version != null && !version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            query += " and sp.wfsVersion = :version";
        }/*from www.  j a  v  a2 s.  co  m*/

        Query q = em.createQuery(query);

        if (orgIds != null) {
            List lijst = Arrays.asList(orgIds);
            q.setParameter("orgIds", lijst);
        } else {
            q.setParameter("orgIds", null);
        }

        if (version != null && !version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            q.setParameter("version", version);
        }
        spLayers = q.getResultList();
    } else {
        String query = "select distinct new " + "nl.b3p.ogc.utils.SpLayerSummary(l, 'true',sp) "
                + "from WfsLayer l " + "join l.wfsServiceProvider sp";
        if (version != null && !version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            query += " where sp.wfsVersion = :version";
        }

        Query q = em.createQuery(query);
        if (version != null && !version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            q.setParameter("version", version);
        }
        spLayers = q.getResultList();
    }

    List<String> layers = new ArrayList<String>();
    for (SpLayerSummary spls : spLayers) {
        String ln = OGCCommunication.attachSp(spls.getSpAbbr(), spls.getLayerName());
        layers.add(ln);
    }
    return (String[]) layers.toArray(new String[] {});
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try {//from  w w w . j  av  a2 s  .  com
        CurrentUser currentUser = CurrentUser.getInstance();
        Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
        EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
                .createEntityManager();
        entityManager.getTransaction().begin();

        List<TblEntidades> list = (List<TblEntidades>) entityManager.createQuery("select e from TblEntidades e")
                .getResultList();

        for (TblEntidades e : list) {
            String nombreviejo = e.getNombres();
            if (nombreviejo.contains(",")) {
                String[] parts = nombreviejo.split(",");
                e.setNombres(parts[0].trim());
                e.setApellidos(parts[1].trim());
                entityManager.merge(e);
            }
        }

        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
        JOptionPane.showMessageDialog(null, "Nombres actualizados!");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
@Transactional/*from w ww  . ja v a 2  s  .  c o m*/
public synchronized int createHotelRatePlan(HotelRatePlan hotelRatePlan) {
    int retCode = 0;

    List<HotelRatePlan> ratePlans = null;
    EntityManager em = getEm();
    logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
            + hotelRatePlan.getHotelInfo().getHotelCode() + "] begin: ");
    try {
        ratePlans = em.createQuery(
                "select o from HotelRatePlan o where o.ratePlanCode = :ratePlanCode and o.hotelInfo = :hotelInfo")
                .setParameter("ratePlanCode", hotelRatePlan.getRatePlanCode())
                .setParameter("hotelInfo", hotelRatePlan.getHotelInfo()).getResultList();
        if (ratePlans.size() > 0) {
            retCode = 2;
            HotelRatePlan plan0 = ratePlans.get(0);

            //booking rule
            List<HotelRatePlanBookingRule> rules0 = em
                    .createQuery("select o from HotelRatePlanBookingRule o where o.hotelRatePlan = :plan")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanBookingRule rule0 : rules0) {
                em.remove(rule0);
                em.flush();
            }
            if (hotelRatePlan.getHotelRatePlanBookingRules() != null) {
                for (HotelRatePlanBookingRule rule : hotelRatePlan.getHotelRatePlanBookingRules()) {
                    rule.setHotelRatePlan(plan0);
                    em.persist(rule);
                }
            }

            //offer
            List<HotelRatePlanOffer> offers0 = em
                    .createQuery("select o from HotelRatePlanOffer o where o.hotelRatePlan = :plan")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanOffer offer0 : offers0) {
                em.remove(offer0);
                em.flush();
            }
            if (hotelRatePlan.getHotelRatePlanOffers() != null) {
                for (HotelRatePlanOffer offer : hotelRatePlan.getHotelRatePlanOffers()) {
                    offer.setHotelRatePlan(plan0);
                    em.persist(offer);
                }
            }

            //rate
            List<HotelRatePlanRate> rates0 = em.createQuery(
                    "select o from HotelRatePlanRate o where o.hotelRatePlan = :plan order by o.startDate")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanRate rate0 : rates0) {
                for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) {
                    if (rate0.getStartDate().getTime() == rate.getStartDate().getTime()) {
                        em.remove(rate0);
                        em.flush();
                        break;
                    }
                }
            }

            for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) {
                rate.setHotelRatePlan(plan0);
                em.persist(rate);
            }
            logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
                    + hotelRatePlan.getHotelInfo().getHotelCode() + "] updated. ");
        } else {
            em.persist(hotelRatePlan);
            retCode = 1;
            logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
                    + hotelRatePlan.getHotelInfo().getHotelCode() + "] created. ");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        retCode = -1;
        logger.error(Thread.currentThread().getName() + ", createHotelRatePlan["
                + hotelRatePlan.getHotelInfo().getHotelCode() + "]: " + ex.getMessage());
    }

    getEm().detach(hotelRatePlan);
    if (ratePlans != null) {
        for (HotelRatePlan ratePlan : ratePlans) {
            getEm().detach(ratePlan);
        }
    }

    logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
            + hotelRatePlan.getHotelInfo().getHotelCode() + "] end. ");
    return retCode;
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Create query (with set parameters) for {@link #getByClass(String,String)} and
 * {@link #getNumberByClass(String,String)}
 * //from   ww  w .  j  a  v  a  2s .c  o m
 * @param mainClass
 *            the main class to get data sets by
 * @param subClass
 *            the sub class to get data sets by
 * @param count
 *            do count query or not
 * @return query (with set parameters) for {@link #getByClass(String,String)} and
 *         {@link #getNumberByClass(String,String)}
 */
private Query getByClassQuery(String mainClass, String subClass, boolean count) {
    EntityManager em = PersistenceUtil.getEntityManager();
    return em.createQuery("select " + (count ? "count(a)" : "a") + " from " + this.getJpaName()
            + " a join a.classification.classes cl join a.classification.classes cl2 where cl.level=0 and cl.name=:mainClass and cl2.level=1 and cl2.name=:subClass")
            .setParameter("mainClass", mainClass).setParameter("subClass", subClass);
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Create query (with set parameters) for {@link #getByClass(String)} and {@link #getNumberByClass(String)}
 * /*  w w  w .j  av a2 s .c  o  m*/
 * @param mainClass
 *            the main class to get data sets by
 * @param count
 *            do count query or not
 * @return query (with set parameters) for {@link #getByClass(String)} and {@link #getNumberByClass(String)}
 */
private Query getByClassQuery(String mainClass, boolean count) {
    EntityManager em = PersistenceUtil.getEntityManager();
    return em
            .createQuery("select " + (count ? "count(a)" : "a") + " from " + this.getJpaName()
                    + " a join a.classification.classes cl where cl.level=0 and cl.name=:className")
            .setParameter("className", mainClass);
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Get the sub classes for provided class name and level
 * //from  ww  w. java2 s  .c  o m
 * @param className
 *            class name
 * @param level
 *            level
 * @return sub classes for provided class name and level
 */
@SuppressWarnings("unchecked")
public List<String> getSubClasses(String className, String level) {
    EntityManager em = PersistenceUtil.getEntityManager();

    Query q = em.createQuery("select distinct cl.name from " + this.getJpaName()
            + " a join a.classification.classes cl join a.classification.classes cl2 where cl.level=:level and cl2.name=:className order by cl.name");
    q.setParameter("level", Integer.parseInt(level));
    q.setParameter("className", className);

    return q.getResultList();
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

private List<T> getDatasetsFromRootDs(IDataStockMetaData dataStock, int startIndex, int pageSize) {
    EntityManager em = PersistenceUtil.getEntityManager();
    Query query = em.createQuery("SELECT a FROM " + this.getJpaName() + " a WHERE a.rootDataStock.id=:dsId");

    query.setParameter("dsId", dataStock.getId());
    query.setFirstResult(startIndex);/*from   w w  w . j av  a 2 s  . com*/
    query.setMaxResults(pageSize);

    return query.getResultList();
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

private long getDatasetsFromRootDsCount(IDataStockMetaData dataStock) {
    EntityManager em = PersistenceUtil.getEntityManager();
    Query query = em
            .createQuery("SELECT COUNT(a) FROM " + this.getJpaName() + " a WHERE a.rootDataStock.id=:dsId");

    query.setParameter("dsId", dataStock.getId());

    Long resultCount = (Long) query.getSingleResult();

    return resultCount.longValue();
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

private List<T> getDatasetsFromNonRootDs(IDataStockMetaData dataStock, int startIndex, int pageSize) {
    final String dsField = this.getDataStockField();
    StringBuilder sb = new StringBuilder("SELECT b FROM DataStock a LEFT JOIN a.").append(dsField)
            .append(" b WHERE a.id=:dsId");

    EntityManager em = PersistenceUtil.getEntityManager();
    Query query = em.createQuery(sb.toString());

    query.setParameter("dsId", dataStock.getId());
    query.setFirstResult(startIndex);/*from   ww  w  .  ja  va2s . c o  m*/
    query.setMaxResults(pageSize);

    return query.getResultList();
}