Example usage for javax.persistence.criteria CriteriaBuilder createQuery

List of usage examples for javax.persistence.criteria CriteriaBuilder createQuery

Introduction

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

Prototype

<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

Source Link

Document

Create a CriteriaQuery object with the specified result type.

Usage

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * /*from  w w w  . j  a  va2s .c o  m*/
 * @param first
 * @param count
 * @param adapter
 * @return
 */
public List<CubesMetricMeasurement> getAllByAdapter(int first, int count, AdapterSettings adapter) {
    logger.info("Get measurements for adapter: " + adapter);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.adapter), adapter);
    query.orderBy(cb.asc(root.get(CubesMetricMeasurement_.self)));
    query.where(condition);
    return em.createQuery(query).setFirstResult(first).setMaxResults(count).getResultList();
}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * //from   www.j  a  va 2 s .  c  o m
 * @param metric
 * @return
 * @throws uQasarException
 */
public List<CubesMetricMeasurement> getMeasurementsForMetric(String metric) throws uQasarException {
    logger.info("Get measurements for metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.cubesMetric), metric);
    query.where(condition);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList();
}

From source file:cn.guoyukun.spring.jpa.repository.support.SimpleBaseRepository.java

/**
 * Creates a new count query for the given {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param spec can be {@literal null}./*from w ww.ja va2s  .  c  o  m*/
 * @return
 */
protected TypedQuery<Long> getCountQuery(Specification<M> spec) {

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);

    Root<M> root = applySpecificationToCriteria(spec, query);

    if (query.isDistinct()) {
        query.select(builder.countDistinct(root));
    } else {
        query.select(builder.count(root));
    }

    TypedQuery<Long> q = em.createQuery(query);
    repositoryHelper.applyEnableQueryCache(q);
    return q;
}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * @param project//from   ww w  .j a  va 2 s .c o  m
 * @return List with all the measurements of a project
 */
public List<CubesMetricMeasurement> getMeasurementByProject(Project project) {
    logger.info("Obtaining measurements for the project: " + project);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.project), project);
    query.where(condition);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList();

}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * /*from  ww w .j ava2s. co m*/
 * @param metric
 * @param date
 * @return
 * @throws uQasarException
 */
public int countMeasurementsByMetricAndDate(String metric, Date date) throws uQasarException {
    logger.info("Count measurements for metric: " + metric + "and date: " + date);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.cubesMetric), metric);
    Predicate condition2 = cb.equal(root.get(CubesMetricMeasurement_.timeStamp), date);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList().size();
}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * /*from   w w  w. j  av  a 2 s. c  o m*/
 * @param metric
 * @return
 * @throws uQasarException
 */
private List<CubesMetricMeasurement> getMeasurementsByMetricAndDate(String metric, Date date)
        throws uQasarException {
    logger.info("Get measurements for metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.cubesMetric), metric);
    Predicate condition2 = cb.equal(root.get(CubesMetricMeasurement_.timeStamp), date);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList();
}

From source file:org.openregistry.core.repository.jpa.JpaPersonRepository.java

public List<Person> searchByCriteria(final SearchCriteria searchCriteria) throws RepositoryAccessException {
    final String givenName = searchCriteria.getGivenName();
    final String familyName = searchCriteria.getFamilyName();
    final Date birthDate = searchCriteria.getDateOfBirth();
    final String searchCriteriaName = searchCriteria.getName();

    // search by role criteria
    final String sponsorNetID = searchCriteria.getSponsorNetID();
    final OrganizationalUnit organizationalUnit = searchCriteria.getOrganizationalUnit();
    final Date roleExpDate = searchCriteria.getRoleExpDate();
    final Type roleType = searchCriteria.getAffiliationType();

    final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();

    final CriteriaQuery<JpaPersonImpl> c = criteriaBuilder.createQuery(JpaPersonImpl.class);
    c.distinct(true);/* w  w  w . j  av a 2  s  . c  o m*/
    final Root<JpaPersonImpl> person = c.from(JpaPersonImpl.class);
    final Join<JpaPersonImpl, JpaNameImpl> name = person.join(JpaPersonImpl_.names);
    final Join<JpaPersonImpl, JpaRoleImpl> role = person.join(JpaPersonImpl_.roles);

    //        person.fetch(JpaPersonImpl_.names);
    //        person.fetch(JpaPersonImpl_.roles);
    //        person.fetch(JpaPersonImpl_.identifiers);

    final Predicate pBirthDate;
    if (birthDate != null) {
        pBirthDate = criteriaBuilder.equal(person.get(JpaPersonImpl_.dateOfBirth), birthDate);
    } else {
        pBirthDate = null;
    }

    Predicate combined = null;

    if (StringUtils.hasText(givenName) && StringUtils.hasText(familyName)) {
        //          final Predicate pGivenName = criteriaBuilder.equal(name.get(JpaNameImpl_.given), givenName );
        Expression<String> pattern = criteriaBuilder.literal((String) givenName + "%");
        final Predicate pGivenName = criteriaBuilder.like(name.get(JpaNameImpl_.given), pattern);
        final Predicate pFamilyName = criteriaBuilder.equal(name.get(JpaNameImpl_.family), familyName);

        combined = criteriaBuilder.and(pGivenName, pFamilyName);
    } else if (StringUtils.hasText(givenName)) {
        combined = criteriaBuilder.equal(name.get(JpaNameImpl_.given), givenName);
    } else if (StringUtils.hasText(familyName)) {
        combined = criteriaBuilder.equal(name.get(JpaNameImpl_.family), familyName);
    } else if (StringUtils.hasText(searchCriteriaName)) {
        final Predicate pGivenName = criteriaBuilder.equal(name.get(JpaNameImpl_.given), searchCriteriaName);
        final Predicate pFamilyName = criteriaBuilder.equal(name.get(JpaNameImpl_.family), searchCriteriaName);
        combined = criteriaBuilder.or(pGivenName, pFamilyName);
    }

    Predicate pRoleCombined = null;

    if (roleType != null) {
        //final Join<JpaPersonImpl,JpaRoleImpl> role = person.join(JpaPersonImpl_.roles);
        //final Join<JpaPersonImpl,JpaRoleImpl> role = name.join(JpaPersonImpl_.roles);
        pRoleCombined = criteriaBuilder.equal(role.get(JpaRoleImpl_.affiliationType), roleType);
    }

    if (organizationalUnit != null && StringUtils.hasText(organizationalUnit.getName())) {
        Predicate orgUnitP = criteriaBuilder.equal(role.get(JpaRoleImpl_.organizationalUnit),
                organizationalUnit);
        if (pRoleCombined != null)
            pRoleCombined = criteriaBuilder.and(pRoleCombined, orgUnitP);
        else
            pRoleCombined = orgUnitP;
        //pRoleCombined = criteriaBuilder.and(pRoleCombined, orgUnitP);
    }

    if (StringUtils.hasText(sponsorNetID)) {
        Person person1 = findByIdentifier(Type.IdentifierTypes.NETID.name(), sponsorNetID);
        if (person1 != null) {
            Predicate sponsorP = criteriaBuilder.equal(role.get(JpaRoleImpl_.sponsorId), person1.getId());
            if (pRoleCombined != null)
                pRoleCombined = criteriaBuilder.and(pRoleCombined, sponsorP);
            else
                pRoleCombined = sponsorP;
        } else {
            pRoleCombined = criteriaBuilder.or();
        }

    }
    if (roleExpDate != null) {
        Predicate expDateP = criteriaBuilder.between(role.get(JpaRoleImpl_.end), new Date(), roleExpDate);
        if (pRoleCombined != null)
            pRoleCombined = criteriaBuilder.and(pRoleCombined, expDateP);
        else
            pRoleCombined = expDateP;
    }

    Predicate pComplete = criteriaBuilder.and();

    if (pBirthDate != null)
        pComplete = criteriaBuilder.and(pComplete, pBirthDate);
    if (combined != null)
        pComplete = criteriaBuilder.and(pComplete, combined);
    if (pRoleCombined != null)
        pComplete = criteriaBuilder.and(pComplete, pRoleCombined);

    c.select(person).where(pComplete);

    //        if (pBirthDate != null && combined != null) {
    //            c.select(person).where(criteriaBuilder.and(pBirthDate, combined));
    //        } else if (pBirthDate != null) {
    //            c.select(person).where(pBirthDate);
    //        } else {
    //            c.select(person).where(combined);
    //        }

    final List<JpaPersonImpl> persons = this.entityManager.createQuery(c).setMaxResults(MAX_QUERY_LIMIT)
            .getResultList();

    return new ArrayList<Person>(persons);
}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * @param project/*from  ww w . j  a v a 2s  . c  o m*/
 * @param metric
 * @return
 */
public CubesMetricMeasurement getLatestMeasurementByProjectAndMetric(String project, String metric) {
    logger.info("Obtaining measurements for the project: " + project + " and metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.cubeName), project);
    Predicate condition2 = cb.equal(root.get(CubesMetricMeasurement_.cubesMetric), metric);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    List<CubesMetricMeasurement> measurements = em.createQuery(query).getResultList();
    CubesMetricMeasurement measurement = null;
    if (measurements != null && measurements.size() > 0 && measurements.get(0) != null) {
        measurement = measurements.get(0); // Get the most "fresh" result 
    }
    return measurement;
}

From source file:net.shopxx.dao.impl.OrderDaoImpl.java

public Page<Order> findPage(Order.Type type, Order.Status status, Member member, Goods goods,
        Boolean isPendingReceive, Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint,
        Boolean isAllocatedStock, Boolean hasExpired, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);//from  w  w  w. j a  v a 2s  .  co m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

From source file:net.shopxx.dao.impl.OrderDaoImpl.java

public Long count(Order.Type type, Order.Status status, Member member, Goods goods, Boolean isPendingReceive,
        Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint, Boolean isAllocatedStock,
        Boolean hasExpired) {//from   w  w  w  .j a v  a2s .  c  o m
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}