Using Criteria for sorting

3

In the system I am developing I am trying to use the criteria to be able to execute a query which I am not able to work with jpql, so I tried to execute according to the material that had been getting to that code.

CriteriaBuilder crite = em.getCriteriaBuilder();
     CriteriaQuery<Peso> query = crite.createQuery(Peso.class);
     Root<Peso> root = query.from(Peso.class);

     Path<String> pathStatus = root.<Mapa>get("mapa").<String>get("status"); 
     Predicate predicateStatus = crite.equal(pathStatus, solicitado)       


     query.where(predicateStatus);

     query.orderBy(orders) <<<<<<<<<<<<<<
     TypedQuery<Peso> q = em.createQuery(query);

The problem is that I need to order my querry, for this I put the orderBy method, (HIGHLIGHTED IN THE CODE) but it only accepts variables of type Orde [] which I do not know how to use. If anyone could inform me how to do this ordination I would greatly appreciate it.

    
asked by anonymous 28.06.2017 / 20:40

1 answer

2

The CriteriaBuilder interface has two methods that return a Order , they are:

/**
 * Create an ordering by the ascending value of the expression.
 *
 * @param x expression used to define the ordering
 *
 * @return ascending ordering corresponding to the expression
 */
 Order asc(Expression<?> x);

and

/**
 * Create an ordering by the descending value of the expression.
 *
 * @param x expression used to define the ordering
 *
 * @return descending ordering corresponding to the expression
 */
 Order desc(Expression<?> x);

In your case it would be done like this:

crite.asc("uma expressão") ou crite.desc("uma expressão")

The "expression" you get with your Root , like this:

root.get("campo que você quer ordenar")

Overall your code would look something like this:

CriteriaBuilder crite = em.getCriteriaBuilder();
CriteriaQuery<Peso> query = crite.createQuery(Peso.class);
Root<Peso> root = query.from(Peso.class);

Path<String> pathStatus = root.<Mapa>get("mapa").<String>get("status"); 
Predicate predicateStatus = crite.equal(pathStatus, solicitado)       


query.where(predicateStatus);

query.orderBy(crite.asc(root.get("propriedade de ordenação"))) //Esse ponto muda
TypedQuery<Peso> q = em.createQuery(query);
    
29.06.2017 / 03:30