Example usage for javax.persistence.criteria CriteriaQuery where

List of usage examples for javax.persistence.criteria CriteriaQuery where

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery where.

Prototype

CriteriaQuery<T> where(Predicate... restrictions);

Source Link

Document

Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.

Usage

From source file:se.inera.intyg.intygstjanst.persistence.model.dao.impl.CertificateDaoImpl.java

@Override
public List<Certificate> findCertificate(Personnummer civicRegistrationNumber, List<String> types,
        LocalDate fromDate, LocalDate toDate, List<String> careUnits) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Certificate> query = criteriaBuilder.createQuery(Certificate.class);
    Root<Certificate> root = query.from(Certificate.class);

    root.fetch("states", JoinType.LEFT);

    if (civicRegistrationNumber == null) {
        return Collections.emptyList();
    }//from   w  w  w .  ja v  a  2 s  .  co m

    List<Predicate> predicates = new ArrayList<>();

    // meta data has to match civic registration number
    predicates.add(criteriaBuilder.equal(root.get("civicRegistrationNumber"),
            DaoUtil.formatPnrForPersistence(civicRegistrationNumber)));

    // filter by certificate types
    if (types != null && !types.isEmpty()) {
        predicates.add(criteriaBuilder.lower(root.<String>get("type")).in(toLowerCase(types)));
    }

    // filter by care unit
    if (careUnits != null && !careUnits.isEmpty()) {
        predicates.add(root.<String>get("careUnitId").in(careUnits));
    }

    query.where(predicates.toArray(new Predicate[predicates.size()]));

    // order by signed date
    query.orderBy(criteriaBuilder.asc(root.get("signedDate")));

    List<Certificate> tmpResult = entityManager.createQuery(query).getResultList();
    List<Certificate> result = filterDuplicates(tmpResult);

    // expect a small number, so lets filter in memory
    return new DateFilter(result).filter(fromDate, toDate);
}

From source file:com.hengyi.japp.execution.Util.java

public static void queryCommand(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<Task> root,
        TaskQueryCommand command) {/*from w ww .j  a v  a  2s.c o m*/
    Predicate p1 = cb.equal(root.get(Task_.charger), command.getOperator());
    ListJoin<Task, Operator> joinFollowers = root.join(Task_.followers, JoinType.LEFT);
    Predicate p2 = cb.equal(joinFollowers.get(Operator_.id), command.getOperator().getId());
    ListJoin<Task, Operator> joinExecutors = root.join(Task_.executors, JoinType.LEFT);
    Predicate p3 = cb.equal(joinExecutors.get(Operator_.id), command.getOperator().getId());
    Predicate p = cb.or(p1, p2, p3);
    if (command.getExecutor() != null) {
        p = cb.and(p, cb.equal(p, cb.isMember(command.getExecutor(), root.get(Task_.executors))));
    }
    if (command.getCustomer() != null) {
        p = cb.and(p, cb.equal(root.get(Task_.customer), command.getCustomer()));
    }
    if (!isBlank(command.getContent())) {
        p = cb.and(p, cb.like(root.get(Task_.content), command.getContentQuery()));
    }
    Collection<TaskType> TaskTypes = command.getTypes();
    if (TaskTypes != null && !TaskTypes.isEmpty()) {
        p = cb.and(p, root.get(Task_.type).in(TaskTypes));
    }
    Collection<TaskStatus> statuses = command.getStatuses();
    if (statuses != null && !statuses.isEmpty()) {
        p = cb.and(p, root.get(Task_.status).in(statuses));
    }
    if (command.getCreateDate() != null) {
        Date createDateStart = LocalDate.fromDateFields(command.getCreateDate()).toDate();
        Date createDateEnd = LocalDate.fromDateFields(command.getCreateDate()).plusDays(1).toDate();
        p = cb.and(p, cb.between(root.get(Task_.logInfo).get(LogInfo_.createDateTime), createDateStart,
                createDateEnd));
        // TODO timestamp date convert
        //p = cb.and(p, cb.equal(root.get(Task_.logInfo).get(LogInfo_.createDateTime).as(java.sql.Date.class), command.getCreateDate()));
    }
    cq.where(p);
}

From source file:net.groupbuy.dao.impl.ProductDaoImpl.java

public List<Product> findList(Goods goods, Set<Product> excludes) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//  w  w w. java2s . c  o  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (goods != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("goods"), goods));
    }
    if (excludes != null && !excludes.isEmpty()) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(root.in(excludes)));
    }
    criteriaQuery.where(restrictions);
    return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getResultList();
}

From source file:net.groupbuy.dao.impl.CouponDaoImpl.java

public Page<Coupon> findPage(Boolean isEnabled, Boolean isExchange, Boolean hasExpired, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Coupon> criteriaQuery = criteriaBuilder.createQuery(Coupon.class);
    Root<Coupon> root = criteriaQuery.from(Coupon.class);
    criteriaQuery.select(root);//w  ww  .j a  va2 s  .co  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (isEnabled != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isEnabled"), isEnabled));
    }
    if (isExchange != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchange"), isExchange));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("endDate").isNotNull(),
                    criteriaBuilder.lessThan(root.<Date>get("endDate"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("endDate").isNull(),
                    criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("endDate"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

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

/**
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return an attached entity if found, null otherwise
 *//*from  ww w. ja va  2  s .co m*/
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public IMarketplaceRating getRating(MarketplaceRatingPK marketplaceRatingPK) {
    final MarketplaceRatingPK tempRatingPK = marketplaceRatingPK;
    MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
    temp.setMarketplaceRatingPK(marketplaceRatingPK);
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(temp)) {
        temp = entityManager.merge(temp);
        return temp;
    } else {
        final TypedQuery<MarketplaceRatingImpl> query = this.createQuery(
                this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() {
                    @Override
                    public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                        final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input
                                .createQuery(MarketplaceRatingImpl.class);
                        final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery
                                .from(MarketplaceRatingImpl.class);
                        Predicate conditionUser = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("userName"),
                                tempRatingPK.getUserName());
                        Predicate conditionPortlet = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("portletDefinition"),
                                tempRatingPK.getPortletDefinition());
                        Predicate allConditions = input.and(conditionPortlet, conditionUser);
                        criteriaQuery.where(allConditions);
                        return criteriaQuery;
                    }
                }));
        List<MarketplaceRatingImpl> results = query.getResultList();
        if (!results.isEmpty()) {
            return results.get(0);
        } else {
            return null;
        }
    }
}

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

/**
 * /*from   ww  w  .  j a v a2s .  c  o  m*/
 * @param metric
 * @return
 * @throws uQasarException
 */
public List<JiraMetricMeasurement> getMeasurementsPerProjectByMetricWithinPeriod(Project project, String metric,
        String period) throws uQasarException {

    List<JiraMetricMeasurement> measurements = new ArrayList<>();
    if (project != null && metric != null && period != null) {
        logger.info(
                "Count measurements for project + " + project.getAbbreviatedName() + " and metric: " + metric);

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
        Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);

        Predicate condition1 = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
        Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.project), project);

        Date from = getDateForPeriod(period);
        Date to = DateTime.now().toDate();
        Predicate condition3 = cb.between(root.get(JiraMetricMeasurement_.timeStamp), from, to);
        //      System.out.println("from:"+from);
        //      System.out.println("to:"+to);

        Predicate condition4 = cb.and(condition1, condition2, condition3);
        query.where(condition4);
        query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
        measurements = em.createQuery(query).getResultList();
    }

    return measurements;
}

From source file:org.broadleafcommerce.common.i18n.dao.TranslationDaoImpl.java

@Override
public Translation readTranslation(TranslatedEntity entityType, String entityId, String fieldName,
        String localeCode, String localeCountryCode, ResultType stage) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Translation> criteria = builder.createQuery(Translation.class);
    Root<TranslationImpl> root = criteria.from(TranslationImpl.class);
    criteria.select(root);//w  ww .jav a2s. com
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(root.get("entityType"), entityType.getFriendlyType()));
    restrictions.add(builder.equal(root.get("entityId"), entityId));
    restrictions.add(builder.equal(root.get("fieldName"), fieldName));
    restrictions.add(builder.like(root.get("localeCode").as(String.class), localeCode + "%"));
    try {
        if (extensionManager != null) {
            extensionManager.getProxy().setup(TranslationImpl.class, stage);
            extensionManager.getProxy().refineRetrieve(TranslationImpl.class, stage, builder, criteria, root,
                    restrictions);
        }
        criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

        TypedQuery<Translation> query = em.createQuery(criteria);
        query.setHint(QueryHints.HINT_CACHEABLE, true);
        List<Translation> translations = query.getResultList();

        if (!translations.isEmpty()) {
            return findBestTranslation(localeCountryCode, translations);
        } else {
            return null;
        }
    } finally {
        if (extensionManager != null) {
            extensionManager.getProxy().breakdown(TranslationImpl.class, stage);
        }
    }
}

From source file:com.zero.dao.impl.BaseDaoImpl.java

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);//from   ww  w  .  j av  a 2s  .  c  o  m
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    addRestrictions(criteriaQuery, filters);

    CriteriaQuery<Long> countCriteriaQuery = criteriaBuilder.createQuery(Long.class);

    for (Root<?> root : criteriaQuery.getRoots()) {
        Root<?> dest = countCriteriaQuery.from(root.getJavaType());
        dest.alias(getAlias(root));
        copyJoins(root, dest);
    }

    Root<?> countRoot = getRoot(countCriteriaQuery, criteriaQuery.getResultType());
    countCriteriaQuery.select(criteriaBuilder.count(countRoot.get("id").<String>get("stcd")));

    if (criteriaQuery.getGroupList() != null) {
        countCriteriaQuery.groupBy(criteriaQuery.getGroupList());
    }
    if (criteriaQuery.getGroupRestriction() != null) {
        countCriteriaQuery.having(criteriaQuery.getGroupRestriction());
    }
    if (criteriaQuery.getRestriction() != null) {
        countCriteriaQuery.where(criteriaQuery.getRestriction());
    }
    return entityManager.createQuery(countCriteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

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

public Long waitingShippingCount(Member member) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);// w  w  w  .j  a  v  a 2  s. c o m
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.notEqual(root.get("orderStatus"), OrderStatus.completed),
            criteriaBuilder.notEqual(root.get("orderStatus"), OrderStatus.cancelled),
            criteriaBuilder.equal(root.get("paymentStatus"), PaymentStatus.paid),
            criteriaBuilder.equal(root.get("shippingStatus"), ShippingStatus.unshipped));
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
            criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("expire"), new Date())));
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

From source file:fi.vm.sade.organisaatio.dao.impl.OrganisaatioDAOImpl.java

@Override
public List<Organisaatio> findByOidList(List<String> oidList, int maxResults) {
    LOG.debug("findByOidList({}, {})", oidList, maxResults);

    // first drop nulls from oidList
    List<String> oidListFiltered = new ArrayList<>();
    for (String oid : oidList) {
        if (oid != null) {
            oidListFiltered.add(oid);//  w  w  w  . ja va2s.co  m
        }
    }

    // perform query
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Organisaatio> query = cb.createQuery(Organisaatio.class);
    Root<Organisaatio> organisaatio = query.from(Organisaatio.class);
    query.orderBy(cb.asc(organisaatio.get("nimihaku")));
    Predicate where = cb.in(organisaatio.get("oid")).value(oidListFiltered);
    query.where(where);
    return getEntityManager().createQuery(query).setMaxResults(maxResults).getResultList();

}