Using Criteria for sorting

Asked

Viewed 509 times

3

In the system I am developing I am trying to use the criteria to be able to execute a query that I am not able to make work by jpql, so I tried to execute according to the material I had getting to 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 querry, for that I put the orderby method, (HIGHLIGHTED IN CODE)but it only accepts variables of type Orde[] which I do not know how to use. If anyone could inform me how I perform this ordination I would greatly appreciate.

1 answer

2


The interface Criteriabuilder has two methods that return one Order, are they:

/**
 * 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 so:

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

The "expression" you get with your Root, thus:

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);
  • 2

    Thanks! Denis! Your post helped me a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.