Example usage for javax.persistence.criteria CriteriaBuilder parameter

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

Introduction

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

Prototype

<T> ParameterExpression<T> parameter(Class<T> paramClass, String name);

Source Link

Document

Create a parameter expression with the given name.

Usage

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

public List<M> findAll(Iterable<ID> ids) {

    return getQuery(new Specification<M>() {
        public Predicate toPredicate(Root<M> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<?> path = root.get(entityInformation.getIdAttribute());
            return path.in(cb.parameter(Iterable.class, "ids"));
        }/*from ww w.  j  a  v  a 2  s  .  c o m*/
    }, (Sort) null).setParameter("ids", ids).getResultList();
}

From source file:ru.portal.services.TableServiceImpl.java

/**
 * TODO    ManyToMany/*from  w  w w  .  j a  va  2  s.  c  o  m*/
 * @param entityClass
 * @param id
 * @return 
 */
@Override
public Map<EntityType<?>, Map<String, String>> findByEntityClassId(String entityClass, String id) {

    try {
        Class<?> cl = Class.forName(entityClass);
        EntityType<?> entityType = em.getEntityManagerFactory().getMetamodel().entity(cl);
        if (entityType != null && entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(entityClass)) {
                Class<?> bindableJavaType = entityType.getBindableJavaType();
                //select

                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
                Root<?> root = cq.from(User.class);

                cq.where(cb.equal(root.get("id"), Long.parseLong(id)));

                TypedQuery<?> query = em.createQuery(cq);
                ParameterExpression<Long> parameter = cb.parameter(Long.class, "id");
                //query.setParameter(parameter, Long.parseLong(id));
                //query.unwrap(org.hibernate.Query.class).getQueryString();

                Object result = query.getSingleResult();

                List<String> columns = getTableOrViewMetaData(entityClass);

                HashMap<String, String> res = new HashMap<>(columns.size());
                Class<? extends Object> clazz = result.getClass();
                for (String fieldName : columns) {
                    try {
                        Field field = clazz.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(result);
                        res.put(fieldName, fieldValue.toString());
                    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                            | IllegalAccessException ex) {
                        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(res);
                Map<EntityType<?>, Map<String, String>> hm = new HashMap<>();
                hm.put(entityType, res);
                return hm;

            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:edu.sabanciuniv.sentilab.sare.models.base.documentStore.PersistentDocumentStore.java

/**
 * Gets identifiers of documents in this store.
 * @param em the {@link EntityManager} to get the documents from.
 * @return an {@link Iterable} of document identifiers.
 *//*from   w ww . j  a  v  a 2  s .c o m*/
public Iterable<byte[]> getDocumentIds(EntityManager em) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class);
    Root<PersistentDocument> doc = cq.from(PersistentDocument.class);
    cq.multiselect(doc.get("id"))
            .where(cb.equal(doc.get("store"), cb.parameter(PersistentDocumentStore.class, "store")));
    TypedQuery<byte[]> tq = em.createQuery(cq);
    tq.setParameter("store", this);
    return tq.getResultList();
}

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

/**
 * SELECT e FROM jpa_query_employee e WHERE e.name= :name
 *//*from  w w  w . j  a v a2  s .  c o m*/
@Transactional
public void doParameterQuery() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> e = c.from(Employee.class);

    // parameter, equal to ":name"
    ParameterExpression<String> paraName = cb.parameter(String.class, "name");

    // e.name = ":name"
    c.select(e).where(cb.equal(e.get("name"), paraName));

    // set param value
    TypedQuery<Employee> query = em.createQuery(c);
    query.setParameter("name", "employee_1");
    List<Employee> result = query.getResultList();
    ResultViewer.showResult(result, "criteria query : parameter query");
}

From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public Map<MemberRegister, Integer> fetchTotalPointsPerMemberRegister(QuestionnaireType questionnaireType) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();
    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> questionnaireTypeParam = cb.parameter(QuestionnaireType.class,
            "questionnaireType");
    Expression<Integer> value = evaluationAnswer.get(EvaluationAnswer_.answer).get(QuestionChoicesDef_.value)
            .as(Integer.class);
    cq.multiselect(evaluationAnswer.get(EvaluationAnswer_.memberRegister).alias("memberRegister"),
            value.alias("value"));
    cq.where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireTypeParam));
    TypedQuery<Tuple> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", questionnaireType);
    List<Tuple> result = query.getResultList();
    Map<MemberRegister, Integer> pointsPerMemberRegister = result.stream().collect(Collectors.groupingBy(t -> {
        return t.get("memberRegister", MemberRegister.class);
    }, Collectors.summingInt(t -> t.get("value", Integer.class))));

    return pointsPerMemberRegister;
}

From source file:org.medici.bia.dao.volume.VolumeDAOJpaImpl.java

/**
 * {@inheritDoc}//from w w  w.  j av a 2s  .  c o m
 */
@Override
public Volume findVolume(Integer volNum, String volLetExt) {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Volume> criteriaQuery = criteriaBuilder.createQuery(Volume.class);
    Root<Volume> root = criteriaQuery.from(Volume.class);

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLetExt = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum),
            StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt"))
                    : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLetExt),
            criteriaBuilder.equal(root.<Boolean>get("logicalDelete"), Boolean.FALSE)));

    // Set values in predicate's elements  
    TypedQuery<Volume> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        typedQuery.setParameter("volLetExt", volLetExt);
    }

    List<Volume> result = typedQuery.getResultList();

    if (result.size() == 1) {
        return result.get(0);
    } else {
        return null;
    }
}

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);/*from  www.  j a v  a 2s . co m*/
    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.uni.dao.etc.UniJpaRepository.java

public List<T> findAll(Iterable<ID> ids) {

    return getQuery(new Specification<T>() {
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<?> path = root.get(entityInformation.getIdAttribute());
            return path.in(cb.parameter(Iterable.class, "ids"));
        }/*w w  w.  j av  a2 s .com*/
    }, (Sort) null).setParameter("ids", ids).getResultList();
}

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

/**
 * subquery: in/* ww w.j a  va 2s  .co  m*/
 * SELECT e FROM jpa_query_employee e WHERE e IN (SELECT emp FROM jpa_query_project p JOIN p.employees pe WHERE p.name = :projectname)
 */
@Transactional
public void doWhere1() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> e = c.from(Employee.class);

    // subquery
    Subquery<Employee> sq = c.subquery(Employee.class);
    Root<Project> p = sq.from(Project.class);
    Join<Project, Employee> pe = p.join("employees");
    sq.select(pe).where(cb.equal(p.get("name"), cb.parameter(String.class, "projectname")));

    //
    c.select(e).where(cb.in(e).value(sq));
}

From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public Long fetchNumberOfMemberRegistersWithoutTerms() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<MemberRegister> memberRegister = cq.from(MemberRegister.class);
    Subquery<Long> sq = cq.subquery(Long.class);
    Root<EvaluationAnswer> evaluationAnswer = sq.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");
    sq.select(evaluationAnswer.get("memberRegister").get("id"))
            .where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireType));
    cq.select(cb.count(memberRegister.get("id"))).where(cb.not(cb.in(memberRegister.get("id")).value(sq)));
    TypedQuery<Long> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", QuestionnaireType.TERMS_OF_CONDITION);
    return query.getSingleResult();
}