Query criteria for finding strings using a specific subclass

I will start with a disinfected example.

In my system, I have a Car class. The car has several fields, including an instance of the GearShift of the GearShift class.

public class Car {
    private GearShift gearShift;

    // Snip
}

GearShift is an abstract class from which AutomaticShift and StickShift are inherited. This maps to Hibernate as a table per subclass.

Now, let's say I want to get cars with an automatic transmission. I would prefer to do this using the Hibernate criteria, so I present the "ofType" constraint that I can add as shown below.

getSession().createCriteria(Car.class)
    .add(Restrictions.ofType(AutomaticShift.class)
    .list();

Is this possible anyway?

+3
source share
2 answers

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();
+9

, , 2 :

  • :

    List<Long> automaticGearIds = getSession().createCriteria(AutomaticShift.class)
                                            .setProjection(Projections.distinct(Property.forName("id")))
                                            .list();
    
  • :

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

All Articles