Example usage for javax.persistence.criteria CriteriaQuery from

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

Introduction

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

Prototype

<X> Root<X> from(Class<X> entityClass);

Source Link

Document

Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.

Usage

From source file:org.osiam.resource_server.storage.dao.ResourceDao.java

public <T extends ResourceEntity, V> boolean isUniqueAttributeAlreadyTaken(String attributeValue, String id,
        SingularAttribute<? super T, V> attribute, Class<T> clazz) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<T> resource = cq.from(clazz);

    cq.select(cb.countDistinct(resource));

    Predicate predicate = cb.equal(resource.get(attribute), attributeValue);
    if (id != null) {
        Predicate ignoreId = cb.notEqual(resource.get(ResourceEntity_.id), id);
        predicate = cb.and(predicate, ignoreId);
    }//ww w  .  ja v  a2  s  .c  o m
    cq.where(predicate);

    TypedQuery<Long> countQuery = em.createQuery(cq);

    return countQuery.getSingleResult() > 0;
}

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

/**
 * {@inheritDoc}/*w  w  w . j ava 2  s.c  om*/
 */
public long getTransactionsCount(Map<String, Object> filters, long userId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);
    Root<Transaction> root = query.from(Transaction.class);
    query.select(builder.count(root));
    addFilterCriteria(userId, filters, builder, root, query);

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

}

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

public int count() {
    javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(entityManager.getCriteriaBuilder().count(rt));
    javax.persistence.Query q = entityManager.createQuery(cq);
    return Integer.valueOf(q.getSingleResult().toString());
}

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  w w  w.  ja 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: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   w  w w. j  a va2 s .  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/* w ww.  jav  a2 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:org.osiam.resource_server.storage.dao.ResourceDao.java

private <T extends ResourceEntity> long getTotalResults(Class<T> clazz, Subquery<Long> internalIdQuery) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> resourceQuery = cb.createQuery(Long.class);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    resourceQuery.select(cb.count(resourceRoot))
            .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    Long total = em.createQuery(resourceQuery).getSingleResult();

    return total;
}

From source file:org.sloth.persistence.impl.ObservationDaoImpl.java

@Override
public Collection<Observation> getAll() {
    CriteriaQuery<Observation> cq = getEntityManager().getCriteriaBuilder().createQuery(Observation.class);
    cq.select(cq.from(Observation.class));
    Collection<Observation> list = getEntityManager().createQuery(cq).getResultList();
    logger.info("Getting all Observations; Found: {}", list.size());
    return list;//w ww .ja  va2s. c o m
}

From source file:utils.jpa.EntityResource.java

public int getAllCount(TableSearchQuery tb, List<String> fieldsSearchBy) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> root = cq.from(entityClass);
    cq.select(cb.count(root));//www  .  j av  a 2  s .  c  o  m
    Query query = tb.createQuery(em, cb, cq, root);
    if (query == null) {
        query = createCommonQuery(cb, cq, root, tb, fieldsSearchBy);
    }
    try {
        return ((Long) query.getSingleResult()).intValue();
    } catch (NoResultException ex) {
        return 0;
    }
}

From source file:net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper.java

/**
 * Gets the quantity./*from   ww  w . j ava  2  s  .c  o  m*/
 * 
 * @param dbAccess
 *            the db access
 * @param target
 *            the target
 * @return the quantity
 * @since 28/08/2014, 11:20:27 PM
 */
public int getQuantity(EntityManager dbAccess, Class<Entity> target) {
    CriteriaQuery<Long> cq = dbAccess.getCriteriaBuilder().createQuery(Long.class);
    Root<Entity> rt = cq.from(target);
    cq.select(dbAccess.getCriteriaBuilder().count(rt));
    Query q = dbAccess.createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}