Example usage for javax.persistence.criteria CriteriaBuilder createQuery

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

Introduction

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

Prototype

<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

Source Link

Document

Create a CriteriaQuery object with the specified result type.

Usage

From source file:se.kth.csc.persist.JPAStore.java

@Override
public Account fetchAccountWithPrincipalName(String principalName) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Account> q = cb.createQuery(Account.class);

    Root<Account> account = q.from(Account.class);

    try {/*from w  ww. ja v  a 2 s.  c om*/
        return entityManager
                .createQuery(
                        q.select(account).where(cb.equal(account.get(Account_.principalName), principalName)))
                .getSingleResult();
    } catch (NoResultException e) {
        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);/*w w  w .  j  a  v a  2s  .  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:se.kth.csc.persist.JPAStore.java

@Override
public Account fetchNewestAccount() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Account> q = cb.createQuery(Account.class);

    Root<Account> account = q.from(Account.class);

    List<Account> candidates = entityManager
            .createQuery(q.select(account).orderBy(cb.desc(account.get(Account_.id)))).setMaxResults(1)
            .getResultList();//  w w w . ja va2s  .  c  o  m

    if (candidates.isEmpty()) {
        return null;
    } else {
        return candidates.get(0);
    }
}

From source file:core.commonapp.server.dao.party.PersonDaoHibernateImpl.java

@Override
@Transactional/*w  w w  .j ava2s.c o  m*/
public List<Person> findAllContactPeople(Integer partyId) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Person> query = builder.createQuery(Person.class);

    Root<Person> contactPerson = query.from(Person.class);
    Join<Person, PartyRelationship> partyToRelationships = contactPerson.join("partyToRelationships");

    query.where(builder.equal(partyToRelationships.get("partyFrom.partyId"), partyId),
            builder.isNull(partyToRelationships.get("thruDate")));

    List<Person> people = getEntityManager().createQuery(query).getResultList();

    PartyDaoHibernateImpl.lazyLoad((Party) people, true, true, false, false);

    return people;
}

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

/**
 * {@inheritDoc}/*  w  w w  .j  a v  a2s .  c  o  m*/
 */
public long getStatementsCount(Map<String, Object> filters, long userId) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(builder.count(root));
    addFilterCriteria(userId, filters, builder, root, query);

    return entityManager.createQuery(query).getSingleResult();
}

From source file:se.kth.csc.persist.JPAStore.java

@Override
public QueuePosition fetchQueuePositionWithQueueAndUser(String queueName, String userName) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<QueuePosition> q = cb.createQuery(QueuePosition.class);

    Root<QueuePosition> queuePosition = q.from(QueuePosition.class);
    Join<QueuePosition, Queue> queue = queuePosition.join(QueuePosition_.queue);
    Join<QueuePosition, Account> account = queuePosition.join(QueuePosition_.account);

    try {//from ww  w  .j a v  a 2s . c  o  m
        return entityManager
                .createQuery(
                        q.select(queuePosition)
                                .where(cb.and(cb.equal(queue.get(Queue_.name), queueName),
                                        cb.equal(account.get(Account_.principalName), userName))))
                .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:com.qpark.eip.core.spring.auth.dao.AuthorityDao.java

/**
 * Get the total number of calls for that date.
 *
 * @param userName/*from   w  w w .  j  av  a 2 s  .  c o m*/
 *            the user name.
 * @param serviceName
 *            the service name.
 * @param operationName
 *            the operation name.
 * @param date
 *            the date the calls are recorded.
 * @return the number of calls.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public int getCurrentRequestNumber(final String userName, final String serviceName, final String operationName,
        final Date date) {
    int requests = 0;
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    Root<SystemUserLogType> c = q.from(SystemUserLogType.class);
    q.where(cb.equal(c.<String>get(SystemUserLogType_.context), this.contextNameProvider.getContextName()),
            cb.equal(c.<String>get(SystemUserLogType_.userName), userName),
            cb.equal(c.<String>get(SystemUserLogType_.serviceName), serviceName),
            cb.equal(c.<String>get(SystemUserLogType_.operationName), operationName),
            cb.equal(c.<Date>get(SystemUserLogType_.logDateItem), date));

    TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);
    try {
        SystemUserLogType log = typedQuery.getSingleResult();
        requests = log.getRequestsGranted();
    } catch (Exception e) {
        requests = 0;
    }
    return requests;
}

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

public Long count(Member member, Boolean read) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Message> criteriaQuery = criteriaBuilder.createQuery(Message.class);
    Root<Message> root = criteriaQuery.from(Message.class);
    criteriaQuery.select(root);//from  www . j a  v  a 2  s. c o m
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNull(root.get("forMessage")),
            criteriaBuilder.equal(root.get("isDraft"), false));
    if (member != null) {
        if (read != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("sender"), member),
                                    criteriaBuilder.equal(root.get("senderDelete"), false),
                                    criteriaBuilder.equal(root.get("senderRead"), read)),
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("receiver"), member),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false),
                                    criteriaBuilder.equal(root.get("receiverRead"), read))));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("sender"), member),
                                    criteriaBuilder.equal(root.get("senderDelete"), false)),
                            criteriaBuilder.and(criteriaBuilder.equal(root.get("receiver"), member),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false))));
        }
    } else {
        if (read != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("sender")),
                                    criteriaBuilder.equal(root.get("senderDelete"), false),
                                    criteriaBuilder.equal(root.get("senderRead"), read)),
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("receiver")),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false),
                                    criteriaBuilder.equal(root.get("receiverRead"), read))));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("sender")),
                                    criteriaBuilder.equal(root.get("senderDelete"), false)),
                            criteriaBuilder.and(criteriaBuilder.isNull(root.get("receiver")),
                                    criteriaBuilder.equal(root.get("receiverDelete"), false))));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

/**
 * {@inheritDoc}/*from  ww  w.  ja va  2s.  co  m*/
 */
@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.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * {@inheritDoc}//from  w w w  .  j  av  a  2  s  . c o m
 */
public List<Statement> getStatements(int start, int limit, String sortField, String sortOrder,
        Map<String, Object> filters, long userId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    addSorting(sortField, sortOrder, query, builder, root);
    addFilterCriteria(userId, filters, builder, root, query);
    return entityManager.createQuery(query).setFirstResult(start).setMaxResults(limit).getResultList();
}