我想使用 JPA CriteriaBuilder 创建一个查询,并且我想添加一个ORDER BY
子句。这是我的实体:
@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
}
嵌入式类是:
@Embeddable
public class IdBrand implements Serializable {
@ManyToOne
private Edition edition;
private String name;
}
我构建查询的方式是这样的:
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();
这里是调用的函数:
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)));
}
}
如果我尝试设置sortCol
为类似"id.name"
我收到以下错误:
javax.ejb.EJBException:java.lang.IllegalArgumentException:无法针对路径解析属性 [id.name]
知道我怎么能做到这一点吗?我试着在网上搜索,但我找不到关于这个的提示......如果我能ORDER BY
在有@ManyToOne
关系时做类似的事情也会很棒(例如,"id.edition.number"
)