Question:
In the system that I'm developing, I'm trying to use the criteria to be able to execute a query which I'm not able to make work by jpql, so I tried to execute it according to the material that I had, reaching this 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 query, for that I put the orderBy method, (HIGHLIGHTED IN THE CODE) but it only accepts variables of type Orde[] which I don't know how to use. If anyone could inform me how I carry out this ordination I would be very grateful.
Answer:
The CriteriaBuilder interface has two methods that return an 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);
e
/**
* 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);