JPA criteria query, order on class

2019-04-07 02:27发布

问题:

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