Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA criteria query, order on class

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

like image 555
Jeroen Avatar asked Nov 15 '10 20:11

Jeroen


1 Answers

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
like image 135
Pascal Thivent Avatar answered Nov 16 '22 01:11

Pascal Thivent