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:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public ConcurrentMap<TermsOfConditionStatus, AtomicLong> fetchTermsOfCompetitionStatistic() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<EvaluationAnswer> cq = cb.createQuery(EvaluationAnswer.class);
    Root<EvaluationAnswer> evaluationAnswer = cq.from(EvaluationAnswer.class);
    Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer);
    Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef
            .join(QuestionChoicesDef_.evaluationQuestionDef);
    ParameterExpression<QuestionnaireType> questionnaireType = cb.parameter(QuestionnaireType.class,
            "questionnaireType");
    cq.select(evaluationAnswer);// ww w. j a va2  s .c om
    cq.where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireType));
    TypedQuery<EvaluationAnswer> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", QuestionnaireType.TERMS_OF_CONDITION);
    List<EvaluationAnswer> evaluationAnswers = query.getResultList();

    ConcurrentMap<TermsOfConditionStatus, AtomicLong> distributionByTermsOfCompetitionStatus = new ConcurrentHashMap<>();

    List<EvaluationQuestionnaireDefEnum> questionnaireDef = Arrays
            .asList(EvaluationQuestionnaireDefEnum.values());
    long numberOfQuestion = questionnaireDef.stream()
            .filter(q -> q.getQuestionnaireType().equals(QuestionnaireType.TERMS_OF_CONDITION))
            .collect(Collectors.counting());

    List<MemberRegister> memberRegisters = evaluationAnswers.stream()
            .filter(StreamUtil.distinctByKey((EvaluationAnswer e) -> e.getMemberRegister().getId()))
            .map(EvaluationAnswer::getMemberRegister).collect(Collectors.toList());
    memberRegisters.stream().forEach((memberRegister) -> {
        TermsOfConditionStatus termsOfConditionStatus = TermsOfConditionStatus.NONE;
        if (evaluationAnswers.stream().filter(m -> m.getMemberRegister().equals(memberRegister))
                .count() == numberOfQuestion) {
            boolean isValid = evaluationAnswers.stream()
                    .filter(m -> m.getMemberRegister().equals(memberRegister))
                    .allMatch(e -> e.getAnswer().getLabel()
                            .equals(messageSource.getMessage("QuestionChoicesDef.yes", null, Locale.ENGLISH)));
            termsOfConditionStatus = isValid ? TermsOfConditionStatus.VALID : TermsOfConditionStatus.INVALID;
        }
        distributionByTermsOfCompetitionStatus.putIfAbsent(termsOfConditionStatus, new AtomicLong(0));
        distributionByTermsOfCompetitionStatus.get(termsOfConditionStatus).incrementAndGet();
    });

    return distributionByTermsOfCompetitionStatus;
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<ImageProductDTO> getImageProductDTOs() {
    return transactionTemplate.execute(new TransactionCallback<List<ImageProductDTO>>() {
        @Override/*from   ww  w. j a  v  a  2  s .c o m*/
        public List<ImageProductDTO> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<ImageProductDTO> query = cb.createQuery(ImageProductDTO.class);
            Root<Image> imageRoot = query.from(Image.class);
            Join<Image, Product> productJoin = imageRoot.join(Image_.product);
            query.distinct(true);
            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%"));
            criteria.add(cb.gt(imageRoot.get(Image_.index), 0));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            query.select(cb.construct(ImageProductDTO.class, imageRoot.get(Image_.name),
                    productJoin.get(Product_.name))).orderBy(cb.asc(imageRoot.get(Image_.name)));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

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

public Page<Product> findPage(Member member, Pageable pageable) {
    if (member == null) {
        return new Page<Product>(Collections.<Product>emptyList(), 0, pageable);
    }/*from w w w.j  av  a 2 s. c  o m*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);
    criteriaQuery.where(criteriaBuilder.equal(root.join("favoriteMembers"), member));
    return super.findPage(criteriaQuery, pageable);
}

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public int itemsDateRangeCount(Date startDate, Date endDate) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(TxInstance.class);
    Root<TxInstance> rt = cq.from(TxInstance.class);
    cq.select(cb.count(rt.get(TxInstance_.activityinstanceser)));
    cq.where(cb.and(rt.get(TxInstance_.completed).isNotNull(),
            cb.between(rt.get(TxInstance_.completed), startDate, endDate)));

    Query q = em.createQuery(cq);
    return ((Long) (q.getSingleResult())).intValue();
}

From source file:com.aimdek.ccm.dao.impl.TransactionRepositoryImpl.java

/**
 * {@inheritDoc}/*from   w  w w  . ja  v  a  2s.  c o  m*/
 */
public List<Transaction> searchTransaction(String searchTerm) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class);
    Root<Transaction> root = query.from(Transaction.class);
    query.select(root);
    Predicate customerName = builder.like(root.<String>get(FIELDCONSTANT_CUSTOMERNAME),
            MODULO + searchTerm + MODULO);
    Predicate creditCardNumber = builder.like(root.<String>get(FIELDCONSTANT_CARDNUMBER),
            MODULO + searchTerm + MODULO);
    Predicate description = builder.like(root.<String>get(FIELD_CONSTANT_DESCRIPTION),
            MODULO + searchTerm + MODULO);
    query.where(builder.or(customerName, creditCardNumber, description));
    return super.find(query);
}

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

private TypedQuery<Entity> buildQueryForProperties(String loginName) {

    CriteriaBuilder builder = getCriteriaBuilder();

    CriteriaQuery<Entity> query = builder.createQuery(Entity.class);
    Root<Entity> entity = query.from(Entity.class);
    Join<PropertyList, Entity> propertyListJoin = entity.join("propertyLists");
    Join<PropertyList, Property> propertiesJoin = propertyListJoin.join("properties");
    List<Predicate> conditions = new ArrayList<>();
    Path<String> propertytypePath = propertiesJoin.get("propertytype");
    conditions.add(builder.like(propertytypePath, "configuration_benutzername"));
    Path<String> propertyvaluePath = propertiesJoin.get("propertyvalue");
    conditions.add(builder.like(propertyvaluePath, loginName));
    query.where(conditions.toArray(new Predicate[conditions.size()]));

    return entityManager.createQuery(query);
}

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

/**
 * //w  w  w. ja  v  a  2  s  .c  om
 * @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:org.easy.criteria.CriteriaProcessor.java

/**
 * Finds a single entity for the given criteria. This ignores the "Select"
 * clause of CriteriaContainer. If you need to selected some specific
 * columns/*from ww w.  j  a  v  a2 s  . co m*/
 * then use "findUniqueTuple" API.
 * 
 * @param criteria
 * @param lockMode
 *            - Pass NULL if your are not managing transaction.
 *            LockModeType.NONE will through exception if no transaction is
 *            active.
 * @return - A single entity or null if no result was found.
 */
public <T> T findUniqueEntity(CriteriaComposer<T> criteria, QueryProperties properties) {
    log.trace("CriteriaProcessor.findUniqueEntity");
    Preconditions.checkNotNull(criteria);

    Class<T> forClass = criteria.getEntityClass();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(forClass);

    log.debug("root =" + forClass.getName());
    Root<T> root = criteriaQuery.from(forClass);

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

    if (criteria != null) {
        criteria.generateJoins(root);
        criteria.generateWhere(criteriaBuilder, wherePredicates);
    }

    criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()]));

    TypedQuery<T> query = entityManager.createQuery(criteriaQuery);

    if (properties != null)
        properties.applyProperties(query);

    return query.getSingleResult();
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<Product> getProducts_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override/*  w  w w  .ja v a 2  s  .c  o  m*/
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Image> imageRoot = query.from(Image.class);
            Join<Image, Product> productJoin = imageRoot.join(Image_.product);
            query.select(productJoin);
            query.distinct(true);
            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%"));
            criteria.add(cb.gt(imageRoot.get(Image_.index), 0));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

From source file:org.businessmanager.dao.GenericDaoImpl.java

@Override
public List<T> findByAttributes(Map<SingularAttribute<T, ?>, Object> theAttributes) {
    CriteriaBuilder queryBuilder = entityManager.getCriteriaBuilder();

    CriteriaQuery<T> criteriaQuery = queryBuilder.createQuery(getPersistenceClass());
    Root<T> rootQuery = criteriaQuery.from(getPersistenceClass());
    CriteriaQuery<T> select = criteriaQuery.select(rootQuery);

    List<Predicate> aPredicateList = new ArrayList<Predicate>();
    Iterator<SingularAttribute<T, ?>> anIterator = theAttributes.keySet().iterator();
    while (anIterator.hasNext()) {
        SingularAttribute<T, ?> aKey = anIterator.next();
        Object aValue = theAttributes.get(aKey);
        Predicate aPredicate = queryBuilder.equal(rootQuery.get(aKey), aValue);
        aPredicateList.add(aPredicate);//from   w  ww.  ja va  2s.  c  om
    }

    select.where(aPredicateList.toArray(new Predicate[0]));
    TypedQuery<T> typedQuery = entityManager.createQuery(select);

    return typedQuery.getResultList();
}