HQL Join Query with InheritanceType.JOINED Based on Subclass' Criteria

Viewed 10

Using a NamedQuery, how to fetch a related table that is using InheritanceType.JOINED based on a field of the subclass?

I have a setup similar to this:

Class with the NamedQuery:

@NamedQuery(<named-query>)
@Entity
@Table(name="T_PERSON")
public class Person {
    private Vehicle vehicle;
}

Abstract Class being referenced by first class:

@Entity
@Table(name = "T_VEHICLE")
@DiscriminatorColumn(name = "vehicleType")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Vehicle {
    private Long vehicleId;
    private String vehicleType;
}

Concrete subclass of the Abstact Class:

@Entity
@Table(name = "T_CAR")
@DiscriminatorValue("CAR")
public class Car extends Vehicle {
    private String make;
}

I'm trying to write a <named-query> in the Person class which will be similar to this SQL:

SELECT * FROM T_PERSON person
LEFT JOIN T_VEHICLE vehicle ON vehicle.VEHICLE_ID = person.VEHICLE_ID
LEFT JOIN T_CAR car on car.VEHICLE_ID = vehicle.VEHICLE_ID
WHERE car.MAKE = 'Honda'

The issue I'm running into is that the Person class only has a reference to the superclass Vehicle, and not the subclass Car, so trying to write a NamedQuery simliar to this fails:

Select person from Person person 
left join person.Vehicle vehicle
where vehicle.make = 'Honda'
1 Answers

The solution was to query it like this:

SELECT person FROM Person person 
INNER JOIN person.vehicle vehicle, Car car
WHERE vehicle.vehicleId = car.vehicleId
    AND car.make = 'Honda'
Related