Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Criteria query looking for rows using a specific subclass

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?

like image 505
SimonPip Avatar asked Dec 02 '25 05:12

SimonPip


1 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();
like image 167
Selim Avatar answered Dec 03 '25 20:12

Selim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!