Reputation: 57757
Is it possible to query for entities of a base class, but order by an attribute of a subclass?
For example, (JPA annotations omitted)
class Base
{
int base;
}
class SubA extends Base
{
int subA;
}
class SubB extends Base
{
int subB;
}
and assume that the database contains instances of all 3 classes.
I want to retrieve all Base instances, polymorphically, sorted on a attribute of the subclass. If the attribute doesn't exist, assume it's null. (Imagine all of these instances are shown in a table, with all attributes, and the user is allowed to sort on any attribute.)
I was hoping for something like:
select b from Base b order by b.subA
but obviously the subA attribute isn't recognised.
Is there some way to attempt a cast so the subA attribute can be used?
Upvotes: 0
Views: 2074
Reputation: 957
Sorry, that isn't possible.
But you can use something like this:
TypedQuery<Base> baseQ = em.createQuery("SELECT b FROM Base b", Base.class);
List<Base> resultList = baseQ.getResultList();
Collections.sort(resultList, new Comparator<Base>() {
@Override
public int compare(Base b1, Base b2) {
...
}
});
Upvotes: 1