Criteria query looking for rows using a specific subclass
-
13-12-2019 - |
Question
I'll start with a sanitized example.
In my system, I've got the class Car. Car has a number of fields, among which is the gearShift instance of class GearShift.
public class Car {
private GearShift gearShift;
// Snip
}
GearShift is an abstract class, from which AutomaticShift and StickShift inherit. This is mapped in Hibernate as table-per-subclass.
Now, say I want to get the cars with automatic gear shifts. I'd prefer doing this through Hibernate criteria, so I'm imagining an "ofType" restriction I can add, like shown below.
getSession().createCriteria(Car.class)
.add(Restrictions.ofType(AutomaticShift.class)
.list();
Is this possible in any way?
Solution
OLD:
How about this?
getSession().createCriteria(AutomaticShift.class).list()
EDIT:
This should do the trick;
getSession().createCriteria(Car.class).createAlias("gearShift", "gs").add(Restrictions.eq("gs.class", AutomaticShift.class)).list();
OTHER TIPS
Maybe it sounds a little like an overhead, but you could do it in 2 steps:
Retrieve all the ids of the Automatic Gears:
List<Long> automaticGearIds = getSession().createCriteria(AutomaticShift.class) .setProjection(Projections.distinct(Property.forName("id"))) .list();
Get all the cars with automatic gears:
return getSession().createCriteria(Car.class).add(Restrictions.in("gearShift.id", automaticGearIds)).list();