I would like to create a query using JPA CriteriaBuilder, and I would like to add a sentence ORDER BY. This is my essence:
@Entity
@Table(name = "brands")
public class Brand implements Serializable {
public enum OwnModeType {
OWNER, LICENCED
}
@EmbeddedId
private IdBrand id;
private String code;
}
Inline class:
@Embeddable
public class IdBrand implements Serializable {
@ManyToOne
private Edition edition;
private String name;
}
And the way I build my query is as follows:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Brand> q = cb.createQuery(Brand.class).distinct(true);
Root<Brand> root = q.from(Brand.class);
if (f != null) {
f.addCriteria(cb, q, root);
f.addOrder(cb, q, root, sortCol, ascending);
}
return em.createQuery(q).getResultList();
And here are the functions that are called:
public void addCriteria(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r) {
}
public void addOrder(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r, String sortCol, boolean ascending) {
if (ascending) {
q.orderBy(cb.asc(r.get(sortCol)));
} else {
q.orderBy(cb.desc(r.get(sortCol)));
}
}
If I try to install sortColon something like "id.name", I get the following error:
javax.ejb.EJBException: java.lang.IllegalArgumentException: cannot resolve attribute [id.name] along the path
Any idea how I could do this? I tried searching on the Internet, but I could not find clues about this ... It would also be great if I could do the same ORDER BYwhen I have an attitude @ManyToOne(for example, "id.edition.number")