Is it possible to order a complex key with JPA and CriteriaBuilder?

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;
    //bunch of other properties
}

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")

+5
2

JPA. JPA :

, , (.). , c.capital.name , "" . . (.) , (, , , ).

id.edition.number, IdBrand (id) .

: root.get("id").get("edition.number");


, , javax.persistence.metamodel.Attribute.PersistentAttributeType . .get(), .join().

, JPA . JPA.

+5

: JPA - API EmbeddedId

:

public void addOrder(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r, String sortCol, boolean ascending) {
    Path<?> p = r;
    String []sortCols = sortCol.split("\\."); // This is a regexp, hence the escape backslash
    for(String sc: sortCols) {
        p = p.get(sc);
    }
    if (ascending) {
        q.orderBy(cb.asc(p));
    } else {
        q.orderBy(cb.desc(p));
    }
}
+1

All Articles