Example usage for javax.persistence.criteria CriteriaQuery select

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

Introduction

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

Prototype

CriteriaQuery<T> select(Selection<? extends T> selection);

Source Link

Document

Specify the item that is to be returned in the query result.

Usage

From source file:org.jdal.dao.jpa.JpaDao.java

/**
 * Gets CriteriaQuery for Page Keys//  w w  w  . ja v  a  2 s.c  om
 * @param page
 * @return CriteriaQuery 
 */
@SuppressWarnings("unchecked")
private TypedQuery<Serializable> getKeyCriteriaQuery(SingularAttribute<? super T, ?> id, Page<T> page) {
    CriteriaQuery<Serializable> keyCriteria = (CriteriaQuery<Serializable>) getCriteria(page);
    Root<T> keyRoot = JpaUtils.findRoot(keyCriteria, getEntityClass());
    keyCriteria.select(keyRoot.<Serializable>get(id.getName()));

    return em.createQuery(keyCriteria);
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Check if the {@link EnterpriseType} with given name and modelVersion
 * exists.//www  .j a  v  a  2  s  .co  m
 *
 * @param name
 *            the name of the {@link EnterpriseType}.
 * @param modelVersion
 *            the version of the model.
 * @return <code>true</code> if exists, else <code>false</code>.
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public boolean existsEnterprise(final String name, final String modelVersion) {
    boolean value = false;

    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<Long> q = cb.createQuery(Long.class);
    final Root<EnterpriseType> f = q.from(EnterpriseType.class);
    q.select(f.<Long>get(EnterpriseType_.hjid));
    q.where(cb.equal(f.<String>get(EnterpriseType_.name), name),
            cb.equal(f.<String>get(EnterpriseType_.modelVersion), modelVersion));
    final TypedQuery<Long> typedQuery = this.em.createQuery(q);
    try {
        final Long l = typedQuery.getSingleResult();
        if (l != null && l.longValue() != 0) {
            value = true;
        }
    } catch (final Exception e) {
        value = false;
    }
    return value;
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * use customize object in select/*from   w ww .j  a  va2s  . co m*/
 */
public void doSelect3() {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    // return type is a customized object
    CriteriaQuery<EmployeeBasicInfo> c = cb.createQuery(EmployeeBasicInfo.class);
    Root<Employee> e = c.from(Employee.class);

    // method 1 : must use multiple select, cannot use select method, because of strong type check
    c.multiselect(e.get("name"));
    showResult(c);

    // method 2 : use select and cb.construct
    c.select(cb.construct(EmployeeBasicInfo.class, e.get("name")));
    showResult(c);

    // method 3 : use multiple select and cb.construct
    // NOTE : UNSUPPORT!
    //      CriteriaQuery<EmployeeBasicInfo> c2 = cb.createQuery(EmployeeBasicInfo.class);
    //      Root<Employee> e2 = c2.from(Employee.class);
    //      c2.multiselect(cb.construct(EmployeeBasicInfo.class, e2.get("name")));
    //      showResult(c2);
}

From source file:com.sapito.db.dao.AbstractDao.java

public List<T> findBySpecificField(String field, Object fieldContent, String predicates,
        LinkedHashMap<String, String> ordering, LinkedList<String> grouping) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> root = cq.from(entityClass);
    Predicate predicate = null;/*  w w  w.  j a  v  a 2  s  .c o  m*/

    if (predicates.equals("equal")) {
        predicate = cb.equal(root.get(field), fieldContent);
    } else if (predicates.equals("likelower")) {
        predicate = cb.like(cb.lower(root.<String>get(field)), fieldContent.toString());
    } else if (predicates.equals("like")) {
        predicate = cb.like(root.<String>get(field), "%" + fieldContent.toString() + "%");
    }

    cq.select(root);
    cq.where(predicate);

    if (ordering != null) {
        Set<String> set = ordering.keySet();
        List<Order> orders = new ArrayList<>();
        for (String orderingField : set) {
            Order order;
            if (ordering.get(orderingField).equals("ASC")) {
                order = cb.asc(root.get(orderingField));
            } else {
                order = cb.desc(root.get(orderingField));
            }
            orders.add(order);
        }
        cq.orderBy(orders);
    }

    if (grouping != null) {
        Iterator iterator = grouping.iterator();
        List<Expression> groups = new LinkedList<>();
        while (iterator.hasNext()) {
            groups.add(root.get(iterator.next().toString()));
        }
        cq.groupBy(groups);
    }

    Query query = entityManager.createQuery(cq);
    query.setMaxResults(MAX_RECORDS_RETURNED);

    return query.getResultList();
}

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:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.findAllSessions = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<SessionImpl>>() {
                @Override//from w  ww  .  j a  va  2s  .  com
                public CriteriaQuery<SessionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<SessionImpl> criteriaQuery = cb.createQuery(SessionImpl.class);
                    final Root<SessionImpl> definitionRoot = criteriaQuery.from(SessionImpl.class);
                    criteriaQuery.select(definitionRoot);

                    return criteriaQuery;
                }
            });
}

From source file:com.hiperium.dao.common.generic.GenericDAO.java

/**
 * Sets the criteria parameters for searching execution.
 *
 * @param entity//from  w  w w.j a v  a  2s . c  o m
 *            the entity with the values for the criteria.
 * @param fieldsToSort
 *            the fields to sort the result.
 */
private <E> CriteriaQuery<E> configureCriteria(E entity, Class<E> entityClass, String... fieldsToSort) {
    CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<E> root = criteriaQuery.from(entityClass);
    criteriaQuery.select(root);
    this.constructQuery(criteriaBuilder, criteriaQuery, root, entity);
    Order[] orderCriteriaList = null;
    if (fieldsToSort.length > 0) {
        orderCriteriaList = new Order[fieldsToSort.length];
        for (int i = 0; i < fieldsToSort.length; i++) {
            if (fieldsToSort[i].startsWith("A,")) {
                if (fieldsToSort[i].contains(".")) {
                    String compositeValue = fieldsToSort[i].substring(2);
                    String compositeName = compositeValue.split("\\.")[0];
                    String compositeFieldName = compositeValue.split("\\.")[1];
                    orderCriteriaList[i] = criteriaBuilder.asc(root.get(compositeName).get(compositeFieldName));
                } else {
                    orderCriteriaList[i] = criteriaBuilder.asc(root.get(fieldsToSort[i].substring(2)));
                }
            } else if (fieldsToSort[i].startsWith("D,")) {
                if (fieldsToSort[i].contains(".")) {
                    String compositeValue = fieldsToSort[i].substring(2);
                    String compositeName = compositeValue.split("\\.")[0];
                    String compositeFieldName = compositeValue.split("\\.")[1];
                    orderCriteriaList[i] = criteriaBuilder
                            .desc(root.get(compositeName).get(compositeFieldName));
                } else {
                    orderCriteriaList[i] = criteriaBuilder.desc(root.get(fieldsToSort[i].substring(2)));
                }
            }
        }
    } else {
        List<String> ids = this.getIdFields(entity);
        orderCriteriaList = new Order[ids.size()];
        int i = 0;
        for (String id : ids) {
            if (id.startsWith(PK_OBJECT_NAME)) {
                String compositeFieldName = id.replace(PK_OBJECT_NAME.concat("."), "");
                orderCriteriaList[i] = criteriaBuilder.asc(root.get(PK_OBJECT_NAME).get(compositeFieldName));
            } else {
                orderCriteriaList[i] = criteriaBuilder.asc(root.get(id));
            }
            i = i + 1;
        }
    }
    criteriaQuery.orderBy(orderCriteriaList);
    return criteriaQuery;
}

From source file:com.sfs.captor.controller.AlternativeFlowAction.java

/**
 * Find testcases associated with this alternative flow
 * <p>// ww w .  j  a v  a 2s .  com
 * Return all testcases where flow name is contained in the testcase name.
 * 
 * @param alternativeFlow
 * @return List of TestCase
 */
private List<TestCase> findTestCases(Flow alternativeFlow) {
    List<TestCase> testCases = new ArrayList<TestCase>();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TestCase> c = cb.createQuery(TestCase.class);
    Root<TestCase> obj = c.from(TestCase.class);
    c.select(obj);
    List<TestCase> list = em.createQuery(c).getResultList();

    for (TestCase testCase : list) {

        if (testCase.getName().indexOf(alternativeFlow.getName()) != -1) {
            testCases.add(testCase);
        }
    }

    return testCases;
}

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);
    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;
        }// ww w . j  a  v a 2 s .  c o m
        distributionByTermsOfCompetitionStatus.putIfAbsent(termsOfConditionStatus, new AtomicLong(0));
        distributionByTermsOfCompetitionStatus.get(termsOfConditionStatus).incrementAndGet();
    });

    return distributionByTermsOfCompetitionStatus;
}

From source file:com.sfs.captor.controller.AlternativeFlowAction.java

/**
 * check for duplicate alternative flow//from   w w  w  . ja v  a2 s  .  c o m
 */
private boolean checkForDuplicateBusinessRule(String name) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<FlowStepRule> c = cb.createQuery(FlowStepRule.class);
    Root<FlowStepRule> obj = c.from(FlowStepRule.class);
    c.select(obj).where(cb.equal(obj.get("name"), name));
    List<FlowStepRule> list = em.createQuery(c).getResultList();
    return (list.size() > 0);
}