Is it possible to order by a composite key with JPA and CriteriaBuilder
Posted
by
Kjir
on Stack Overflow
See other posts from Stack Overflow
or by Kjir
Published on 2012-04-15T10:46:57Z
Indexed on
2012/04/15
11:29 UTC
Read the original article
Hit count: 285
I would like to create a query using the JPA CriteriaBuilder and I would like to add an ORDER BY
clause. This is my entity:
@Entity
@Table(name = "brands")
public class Brand implements Serializable {
public enum OwnModeType {
OWNER, LICENCED
}
@EmbeddedId
private IdBrand id;
private String code;
//bunch of other properties
}
Embedded class is:
@Embeddable
public class IdBrand implements Serializable {
@ManyToOne
private Edition edition;
private String name;
}
And the way I am building my query is like this:
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 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 set sortCol
to something like "id.edition.number"
I get the following error:
javax.ejb.EJBException: java.lang.IllegalArgumentException: Unable to resolve attribute [id.name] against path
Any idea how I could accomplish that? I tried searching online, but I couldn't find a hint about this... Also would be great if I could do a similar ORDER BY
when I have a @ManyToOne
relationship (for instance, "id.edition.number"
)
© Stack Overflow or respective owner