Criteria query looking for rows using a specific subclass

3.2k views Asked by At

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?

2

There are 2 answers

3
Selim On BEST ANSWER

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();
1
Raul Rene On

Maybe it sounds a little like an overhead, but you could do it in 2 steps:

  1. Retrieve all the ids of the Automatic Gears:

    List<Long> automaticGearIds = getSession().createCriteria(AutomaticShift.class)
                                            .setProjection(Projections.distinct(Property.forName("id")))
                                            .list();
    
  2. Get all the cars with automatic gears:

    return getSession().createCriteria(Car.class).add(Restrictions.in("gearShift.id", automaticGearIds)).list();