JPA criteria query, order on class

余生长醉 提交于 2019-12-09 15:55:46

问题


Is there a way with JPA criteria queries to order on class? Imagine the following domain objects:

abstract class Hobby { ... }
class Coding extends Hobby { ... }
class Gaming extends Hobby { ... }

Using regular QL I was able to do

from Hobby h order by h.class

But when I apply the same logic on a criteria query, the runtime exception "unknown attribute" occurs.

CriteriaQuery<Hobby> criteriaQuery = builder.createQuery(Hobby.class);
Root<Hobby> hobbyRoot = criteriaQuery.from(Hobby.class);
criteriaQuery.orderBy(builder.asc(hobbyRoot.get("class"));
List<Hobby> hobbies = entityManager.createQuery(criteriaQuery).getResultList();

JPA implementation used: Hibernate-EntityManager v3.5.5-Final


回答1:


JPA 2.0 introduces a new TYPE expression that allow a query to restrict results based on class types.

You can use a type expression with the Criteria API using Path#type(). So you could try:

CriteriaQuery criteriaQuery = builder.createQuery(Hobby.class);
Root hobbyRoot = criteriaQuery.from(Hobby.class);
criteriaQuery.orderBy(builder.asc(hobbyRoot.type());
List hobbies = entityManager.createQuery(criteriaQuery).getResultList();

While this code compiles, I didn't test it (I'll give it a try tomorrow).

Actually, I wonder if this is legal or if the type() should be part of the select in order to order by it (maybe that's what the criteria query is supposed to generate). Need to check that.

References

  • JPA 2.0 specification
    • Section 4.6.17.4 "Entity Type Expressions"

More resources

  • Java Persistence 2.0 Proposed Final Draft


来源:https://stackoverflow.com/questions/4188397/jpa-criteria-query-order-on-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!