JPA criteria query, order on class
10,323
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
Author by
Jeroen
Updated on June 19, 2022Comments
-
Jeroen almost 2 years
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
-
Jeroen over 13 yearsthanks, too bad hibernate they didn't implement it properly yet. opensource.atlassian.com/projects/hibernate/browse/HHH-4881
-
logan over 12 yearshibernate.onjira.com/browse/HHH-4881 has been resolved in hibernate 4.0.0