简体   繁体   中英

JPA/hibernate order by subclass attribute

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?

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) {
        ...
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM