Example usage for javax.persistence.criteria CriteriaBuilder asc

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

Introduction

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

Prototype

Order asc(Expression<?> x);

Source Link

Document

Create an ordering by the ascending value of the expression.

Usage

From source file:se.inera.intyg.intygstjanst.persistence.model.dao.impl.CertificateDaoImpl.java

@Override
public List<Certificate> findCertificate(Personnummer civicRegistrationNumber, List<String> types,
        LocalDate fromDate, LocalDate toDate, List<String> careUnits) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Certificate> query = criteriaBuilder.createQuery(Certificate.class);
    Root<Certificate> root = query.from(Certificate.class);

    root.fetch("states", JoinType.LEFT);

    if (civicRegistrationNumber == null) {
        return Collections.emptyList();
    }//from  w w  w .j  a  va2  s .co m

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

    // meta data has to match civic registration number
    predicates.add(criteriaBuilder.equal(root.get("civicRegistrationNumber"),
            DaoUtil.formatPnrForPersistence(civicRegistrationNumber)));

    // filter by certificate types
    if (types != null && !types.isEmpty()) {
        predicates.add(criteriaBuilder.lower(root.<String>get("type")).in(toLowerCase(types)));
    }

    // filter by care unit
    if (careUnits != null && !careUnits.isEmpty()) {
        predicates.add(root.<String>get("careUnitId").in(careUnits));
    }

    query.where(predicates.toArray(new Predicate[predicates.size()]));

    // order by signed date
    query.orderBy(criteriaBuilder.asc(root.get("signedDate")));

    List<Certificate> tmpResult = entityManager.createQuery(query).getResultList();
    List<Certificate> result = filterDuplicates(tmpResult);

    // expect a small number, so lets filter in memory
    return new DateFilter(result).filter(fromDate, toDate);
}

From source file:com.carser.viamais.vo.TransactionFilter.java

public List<Transaction> resultList(final EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
    Root<Transaction> transaction = cq.from(Transaction.class);
    cq.where(getPredicates(cb, transaction));
    @SuppressWarnings("rawtypes")
    Path path;/* ww  w .j a va 2  s .  co m*/
    switch (orderBy) {
    case CUSTOMER_NAME:
        path = transaction.get(Transaction_.car).get(Car_.model).get(Model_.name);
        break;
    case DATE:
        path = transaction.get(Transaction_.transactionDate);
        break;
    case PLATE:
        path = transaction.get(Transaction_.car).get(Car_.licensePlate);
        break;
    case TYPE:
        path = transaction.get(Transaction_.type);
        break;
    case YEAR:
        path = transaction.get(Transaction_.car).get(Car_.yearOfModel);
        break;
    default:
        path = transaction.get(Transaction_.car).get(Car_.model).get(Model_.name);
        break;
    }
    switch (order) {
    case DESC:
        cq.orderBy(cb.desc(path));
        break;
    default:
        cq.orderBy(cb.asc(path));
        break;
    }
    TypedQuery<Transaction> query = em.createQuery(cq);
    query.setFirstResult(offset);
    query.setMaxResults(limit);
    return query.getResultList();
}

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

/**
 * Sets the criteria parameters for searching execution.
 *
 * @param entity//  w w w.ja v a 2  s. 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:org.openlmis.migration.tool.openlmis.referencedata.repository.custom.impl.OlmisFacilityTypeApprovedProductRepositoryImpl.java

@Override
public Collection<FacilityTypeApprovedProduct> searchProducts(UUID facilityId, UUID programId,
        boolean fullSupply) {
    checkNotNull(facilityId);//from w  ww  .  j  a v a 2 s.  c  o  m

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<FacilityTypeApprovedProduct> query = builder.createQuery(FacilityTypeApprovedProduct.class);

    Root<FacilityTypeApprovedProduct> ftap = query.from(FacilityTypeApprovedProduct.class);
    Root<Facility> facility = query.from(Facility.class);

    Join<Facility, FacilityType> fft = facility.join("type");

    Join<FacilityTypeApprovedProduct, FacilityType> ft = ftap.join("facilityType");
    Join<FacilityTypeApprovedProduct, ProgramOrderable> pp = ftap.join("programOrderable");

    Join<ProgramOrderable, Program> program = pp.join("program");

    Predicate conjunction = builder.conjunction();
    if (programId != null) {
        conjunction = builder.and(conjunction, builder.equal(program.get("id"), programId));
    }
    conjunction = builder.and(conjunction, builder.equal(fft.get("id"), ft.get("id")));
    conjunction = builder.and(conjunction, builder.equal(facility.get("id"), facilityId));
    conjunction = builder.and(conjunction, builder.equal(pp.get("fullSupply"), fullSupply));
    conjunction = builder.and(conjunction, builder.isTrue(pp.get("active")));

    query.select(ftap);
    query.where(conjunction);

    Join<ProgramOrderable, OrderableDisplayCategory> category = pp.join("orderableDisplayCategory");
    Join<ProgramOrderable, Orderable> orderable = pp.join("product");

    query.orderBy(builder.asc(category.get("orderedDisplayValue").get("displayOrder")),
            builder.asc(category.get("orderedDisplayValue").get("displayName")),
            builder.asc(orderable.get("productCode")));

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

From source file:eu.domibus.common.dao.MessageLogDao.java

public List<MessageLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<MessageLogEntry> cq = cb.createQuery(MessageLogEntry.class);
    Root<MessageLogEntry> mle = cq.from(MessageLogEntry.class);
    cq.select(mle);/*  w  w  w .  j a v  a  2 s .  co  m*/
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "receivedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "receivedTo":
                        predicates.add(cb.lessThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(mle.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(mle.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(mle.get(column)));
        } else {
            cq.orderBy(cb.desc(mle.get(column)));
        }

    }
    final TypedQuery<MessageLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java

/**
 * {@inheritDoc}/*from w  w  w  . j a  v a 2  s  .  c o  m*/
 */
@Override
public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user,
        final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId,
        final String commandName, final String commandId, final Date minStarted, final Date maxStarted,
        final Date minFinished, final Date maxFinished, @NotNull final Pageable page) {
    log.debug("called");

    final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    final Root<JobEntity> root = countQuery.from(JobEntity.class);

    final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags,
            clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName,
            commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted,
            minFinished, maxFinished);

    countQuery.select(cb.count(root)).where(whereClause);

    final Long count = this.entityManager.createQuery(countQuery).getSingleResult();

    // Use the count to make sure we even need to make this query
    if (count > 0) {
        final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class);
        contentQuery.from(JobEntity.class);

        contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user),
                root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished),
                root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName));

        contentQuery.where(whereClause);

        final Sort sort = page.getSort();
        final List<Order> orders = new ArrayList<>();
        sort.iterator().forEachRemaining(order -> {
            if (order.isAscending()) {
                orders.add(cb.asc(root.get(order.getProperty())));
            } else {
                orders.add(cb.desc(root.get(order.getProperty())));
            }
        });

        contentQuery.orderBy(orders);

        final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery)
                .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList();

        return new PageImpl<>(results, page, count);
    } else {
        return new PageImpl<>(Lists.newArrayList(), page, count);
    }
}

From source file:org.openmeetings.app.data.conference.Roommanagement.java

/**
 * gets a list of all availible rooms/*from   w  w w  .j a v a  2 s .c  om*/
 * 
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @return
 */
public List<Rooms> getRoomsInternatl(int start, int max, String orderby, boolean asc) {
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        cq.where(condition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirDao.java

protected TagList getTags(Class<? extends IBaseResource> theResourceType, IIdType theResourceId) {
    String resourceName = null;//  w  w w . ja v a  2 s . c o  m
    if (theResourceType != null) {
        resourceName = toResourceName(theResourceType);
        if (theResourceId != null && theResourceId.hasVersionIdPart()) {
            IFhirResourceDao<? extends IBaseResource> dao = getDao(theResourceType);
            BaseHasResource entity = dao.readEntity(theResourceId);
            TagList retVal = new TagList();
            for (BaseTag next : entity.getTags()) {
                retVal.add(next.getTag().toTag());
            }
            return retVal;
        }
    }

    Set<Long> tagIds = new HashSet<Long>();
    findMatchingTagIds(resourceName, theResourceId, tagIds, ResourceTag.class);
    findMatchingTagIds(resourceName, theResourceId, tagIds, ResourceHistoryTag.class);
    if (tagIds.isEmpty()) {
        return new TagList();
    }
    {
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<TagDefinition> cq = builder.createQuery(TagDefinition.class);
        Root<TagDefinition> from = cq.from(TagDefinition.class);
        cq.where(from.get("myId").in(tagIds));
        cq.orderBy(builder.asc(from.get("mySystem")), builder.asc(from.get("myCode")));
        TypedQuery<TagDefinition> q = myEntityManager.createQuery(cq);
        q.setMaxResults(getConfig().getHardTagListLimit());

        TagList retVal = new TagList();
        for (TagDefinition next : q.getResultList()) {
            retVal.add(next.toTag());
        }

        return retVal;
    }
}

From source file:org.openmeetings.app.data.conference.Roommanagement.java

public List<Rooms> getRoomsInternatlbyType(int start, int max, String orderby, boolean asc,
        String externalRoomType) {
    try {//  ww w. j av a2  s.co m
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        Predicate subCondition = cb.equal(c.get("externalRoomType"), externalRoomType);
        cq.where(condition, subCondition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * query for a list of users//  w w w.j av  a2s.  co  m
 * 
 * @param users_id
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @return
 */
public SearchResult<Users> getUsersList(long user_level, int start, int max, String orderby, boolean asc) {
    try {
        if (authLevelManagement.checkAdminLevel(user_level)) {
            SearchResult<Users> sresult = new SearchResult<Users>();
            sresult.setObjectName(Users.class.getName());
            sresult.setRecords(usersDao.selectMaxFromUsers());

            // get all users
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Users> cq = cb.createQuery(Users.class);
            Root<Users> c = cq.from(Users.class);
            Predicate condition = cb.equal(c.get("deleted"), "false");
            cq.where(condition);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<Users> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<Users> ll = q.getResultList();
            sresult.setResult(ll);
            return sresult;
        }
    } catch (Exception ex2) {
        log.error("[getUsersList] " + ex2);
    }
    return null;
}