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:com.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * Adds the filter criteria./*from   w w  w. ja  v  a  2 s  .c  o  m*/
 *
 * @param userId
 *            the user id
 * @param filters
 *            the filters
 * @param builder
 *            the builder
 * @param root
 *            the root
 * @param query
 *            the query
 */
private void addFilterCriteria(long userId, Map<String, Object> filters, CriteriaBuilder builder,
        Root<Statement> root, CriteriaQuery query) {

    List<Predicate> predicates = new ArrayList<Predicate>();
    if (!filters.isEmpty()) {
        for (Entry<String, Object> entry : filters.entrySet()) {
            if (CommonUtil.isNotNull(root.get(entry.getKey()))) {
                predicates.add(builder.like(root.<String>get(entry.getKey()), entry.getValue() + MODULO));
            }
        }
    }
    if (CommonUtil.isNotNull(userId)) {
        User user = userRepository.findById(userId);
        if (CommonUtil.isNotNull(user) && user.getRole().equals(ROLE_CUSTOMER)) {
            Expression<String> exp = root.get(FIELD_CONSTANT_CREDIT_CARD_ID);
            Predicate predicate = exp.in(retrieveCreditCardIdFromUserId(userId));
            predicates.add(predicate);
        }
    }

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

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaTranslatorImpl.java

@SuppressWarnings("unchecked")
protected TypedQuery<Serializable> constructQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity,
        List<FilterMapping> filterMappings, boolean isCount, boolean isMax, Integer firstResult,
        Integer maxResults, String maxField) {

    CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();

    Class<Serializable> ceilingMarker;
    try {//from   w  w  w . java 2s . c o m
        ceilingMarker = (Class<Serializable>) Class.forName(ceilingEntity);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

    Class<Serializable> securityRoot = rowSecurityService.getFetchRestrictionRoot(
            adminSecurityService.getPersistentAdminUser(), ceilingMarker, filterMappings);
    if (securityRoot != null) {
        ceilingMarker = securityRoot;
    }

    Class<Serializable> ceilingClass = determineRoot(dynamicEntityDao, ceilingMarker, filterMappings);
    CriteriaQuery<Serializable> criteria = criteriaBuilder.createQuery(ceilingMarker);
    Root<Serializable> original = criteria.from(ceilingClass);

    if (isCount) {
        criteria.select(criteriaBuilder.count(original));
    } else if (isMax) {
        criteria.select(criteriaBuilder.max((Path<Number>) ((Object) original.get(maxField))));
    } else {
        criteria.select(original);
    }

    List<Predicate> restrictions = new ArrayList<Predicate>();
    List<Order> sorts = new ArrayList<Order>();
    addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, criteria);

    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    if (!isCount && !isMax) {
        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
        //If someone provides a firstResult value, then there is generally pagination going on.
        //In order to produce consistent results, especially with certain databases such as PostgreSQL, 
        //there has to be an "order by" clause.  We'll add one here if we can.
        if (firstResult != null && sorts.isEmpty()) {
            Map<String, Object> idMetaData = dynamicEntityDao.getIdMetadata(ceilingClass);
            if (idMetaData != null) {
                Object idFldName = idMetaData.get("name");
                Object type = idMetaData.get("type");
                if ((idFldName instanceof String) && (type instanceof SingleColumnType)) {
                    criteria.orderBy(criteriaBuilder.asc(original.get((String) idFldName)));
                }
            }
        }
    }
    TypedQuery<Serializable> response = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);

    if (!isCount && !isMax) {
        addPaging(response, firstResult, maxResults);
    }

    return response;
}

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

/**
 * //from ww  w .j  av  a2s.  c  o  m
 * @param metric
 * @return
 * @throws uQasarException
 */
public int countMeasurementsPerProjectByMetricWithinPeriod(Project project, String metric, String period)
        throws uQasarException {
    logger.info("Count measurements for 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);
    Predicate condition4 = cb.and(condition1, condition2, condition3);
    query.where(condition4);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    Integer res = em.createQuery(query).getResultList().size();
    logger.info("Results' count: " + res);
    return res;
}

From source file:com.netflix.genie.server.metrics.impl.JobCountManagerImpl.java

/**
 * {@inheritDoc}// w  w  w  . j a  v  a2s .c  om
 */
@Override
@Transactional(readOnly = true)
//TODO: Move to specification
public int getNumInstanceJobs(final String hostName, final Long minStartTime, final Long maxStartTime)
        throws GenieException {
    LOG.debug("called");

    final String finalHostName;
    // initialize host name
    if (StringUtils.isBlank(hostName)) {
        finalHostName = NetUtil.getHostName();
    } else {
        finalHostName = hostName;
    }
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    final Root<Job> j = cq.from(Job.class);
    cq.select(cb.count(j));
    final Predicate runningStatus = cb.equal(j.get(Job_.status), JobStatus.RUNNING);
    final Predicate initStatus = cb.equal(j.get(Job_.status), JobStatus.INIT);
    final List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(j.get(Job_.hostName), finalHostName));
    predicates.add(cb.or(runningStatus, initStatus));
    if (minStartTime != null) {
        predicates.add(cb.greaterThanOrEqualTo(j.get(Job_.started), new Date(minStartTime)));
    }
    if (maxStartTime != null) {
        predicates.add(cb.lessThan(j.get(Job_.started), new Date(maxStartTime)));
    }
    //documentation says that by default predicate array is conjuncted together
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    final TypedQuery<Long> query = this.em.createQuery(cq);
    //Downgrading to an int since all the code seems to want ints
    //Don't feel like changing everthing right now can figure out later
    //if need be
    return query.getSingleResult().intValue();
}

From source file:com.eu.evaluation.server.dao.AbstractDAO.java

public boolean isUnique(T entity, String... propertys) {
    if (propertys == null || propertys.length == 0) {
        return true;
    }//from  w  w w.  j av  a2s  . c  om
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = cb.createQuery(entityClass);
        Root<T> root = criteriaQuery.from(entityClass);
        Predicate predicate = null;
        for (String property : propertys) {
            if (predicate == null) {
                predicate = cb.equal(root.get(property), PropertyUtils.getProperty(entity, property));
            } else {
                predicate = cb.and(predicate,
                        cb.equal(root.get(property), PropertyUtils.getProperty(entity, property)));
            }
        }

        if (!StringUtils.isBlank(entity.getId())) {
            predicate = cb.and(predicate, cb.notEqual(root.get("id"), entity.getId()));
        }
        criteriaQuery.where(predicate);

        TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery);
        List<T> result = typedQuery.getResultList();
        return result.isEmpty();
    } catch (Exception e) {
        e.printStackTrace();
        ReflectionUtils.handleReflectionException(e);
    }
    return false;
}

From source file:org.apereo.portal.layout.dlm.FragmentDefinitionDao.java

@Override
public void afterPropertiesSet() throws Exception {
    this.nameParameter = this.createParameterExpression(String.class, "name");
    this.ownerParameter = this.createParameterExpression(String.class, "ownerId");

    this.findAllFragmentsQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<FragmentDefinition>>() {
                @Override/*  www  .  j a v a  2 s .c  o  m*/
                public CriteriaQuery<FragmentDefinition> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<FragmentDefinition> criteriaQuery = cb
                            .createQuery(FragmentDefinition.class);
                    criteriaQuery.from(FragmentDefinition.class);
                    return criteriaQuery;
                }
            });

    this.findFragmentByNameQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<FragmentDefinition>>() {
                @Override
                public CriteriaQuery<FragmentDefinition> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<FragmentDefinition> criteriaQuery = cb
                            .createQuery(FragmentDefinition.class);
                    final Root<FragmentDefinition> fragDefRoot = criteriaQuery.from(FragmentDefinition.class);
                    criteriaQuery.select(fragDefRoot);
                    criteriaQuery.where(cb.equal(fragDefRoot.get(FragmentDefinition_.name), nameParameter));

                    return criteriaQuery;
                }
            });

    this.findFragmentByOwnerQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<FragmentDefinition>>() {
                @Override
                public CriteriaQuery<FragmentDefinition> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<FragmentDefinition> criteriaQuery = cb
                            .createQuery(FragmentDefinition.class);
                    final Root<FragmentDefinition> fragDefRoot = criteriaQuery.from(FragmentDefinition.class);
                    criteriaQuery.select(fragDefRoot);
                    criteriaQuery.where(cb.equal(fragDefRoot.get(FragmentDefinition_.ownerID), ownerParameter));

                    return criteriaQuery;
                }
            });
}

From source file:org.verinice.persistence.CnaTreeElementDaoImpl.java

private TypedQuery<CnaTreeElement> createQueryForScopeKeyValue(Integer scopeId, String key, String value) {
    CriteriaQuery<CnaTreeElement> query = getCriteriaBuilder().createQuery(CnaTreeElement.class);
    Root<CnaTreeElement> rootelement = query.from(CnaTreeElement.class);
    query.select(rootelement);/*w  w  w  .ja  v  a2  s .c om*/

    Join<CnaTreeElement, Entity> entityJoin = rootelement.join("entity", JoinType.LEFT);
    Join<PropertyList, Entity> propertyListJoin = entityJoin.join("propertyLists", JoinType.LEFT);
    Join<PropertyList, Property> propertyJoin = propertyListJoin.join("properties", JoinType.LEFT);

    List<Predicate> conditions = new ArrayList<>();
    if (key != null) {
        conditions.add(getCriteriaBuilder().like(propertyJoin.get("propertytype"), key));
    }
    if (value != null) {
        conditions.add(getCriteriaBuilder().like(propertyJoin.get("propertyvalue"), value));
    }
    if (scopeId != null) {
        conditions.add(getCriteriaBuilder().equal(rootelement.get("scopeId"), scopeId));
    }
    query.where(conditions.toArray(new Predicate[conditions.size()]));

    query.distinct(true);
    return entityManager.createQuery(query);
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

protected List<AbstractResourceRelationEntity> getConsumedRelationsByMasterAndSlave(
        ResourceEntity masterResource, Set<ResourceEntity> slaveResources, String identifier) {
    List<AbstractResourceRelationEntity> consumed = new ArrayList<>();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ConsumedResourceRelationEntity> q = cb.createQuery(ConsumedResourceRelationEntity.class);
    Root<ConsumedResourceRelationEntity> r = q.from(ConsumedResourceRelationEntity.class);
    Predicate masterResourceIs = cb.equal(r.<ResourceEntity>get("masterResource"), masterResource);
    Predicate slaveResourceIn = r.<ResourceEntity>get("slaveResource").in(slaveResources);

    if (!StringUtils.isEmpty(identifier)) {
        Predicate identifierIs = cb.equal(r.<String>get("identifier"), identifier);
        q.where(cb.and(masterResourceIs, slaveResourceIn, identifierIs));
    } else {//  w w w  .  ja v a 2 s  .  c om
        q.where(cb.and(masterResourceIs, slaveResourceIn));
    }

    TypedQuery<ConsumedResourceRelationEntity> query = entityManager.createQuery(q);
    List<ConsumedResourceRelationEntity> result = query.getResultList();
    for (ConsumedResourceRelationEntity rel : result) {
        consumed.add(rel);
    }
    return consumed;
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

protected List<AbstractResourceRelationEntity> getProvidedRelationsByMasterAndSlave(
        ResourceEntity masterResource, Set<ResourceEntity> slaveResources, String identifier) {
    List<AbstractResourceRelationEntity> provided = new ArrayList<>();
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProvidedResourceRelationEntity> q = cb.createQuery(ProvidedResourceRelationEntity.class);
    Root<ProvidedResourceRelationEntity> r = q.from(ProvidedResourceRelationEntity.class);
    Predicate masterResourceIs = cb.equal(r.<ResourceEntity>get("masterResource"), masterResource);
    Predicate slaveResourceIn = r.<ResourceEntity>get("slaveResource").in(slaveResources);

    if (!StringUtils.isEmpty(identifier)) {
        Predicate identifierIs = cb.equal(r.<String>get("identifier"), identifier);
        q.where(cb.and(masterResourceIs, slaveResourceIn, identifierIs));
    } else {//  w ww .ja  v  a  2  s .  c o m
        q.where(cb.and(masterResourceIs, slaveResourceIn));
    }

    TypedQuery<ProvidedResourceRelationEntity> query = entityManager.createQuery(q);
    List<ProvidedResourceRelationEntity> result = query.getResultList();
    for (ProvidedResourceRelationEntity rel : result) {
        provided.add(rel);
    }
    return provided;
}

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

public BigDecimal createOrderAmount(Date beginDate, Date endDate) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BigDecimal> criteriaQuery = criteriaBuilder.createQuery(BigDecimal.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(criteriaBuilder.sum(root.<BigDecimal>get("amount")));
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
    }/*from   w  ww. ja  v a2s.  c  om*/
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
    }
    criteriaQuery.where(restrictions);
    BigDecimal result = entityManager.createQuery(criteriaQuery).getSingleResult();
    return result != null ? result : BigDecimal.ZERO;
}