Hibernate query fetches data from subclass

170 Views Asked by At

I am using Table per concrete class strategy

Vehicle
TransportationVehicle extends Vehicle
PassengerVehicle extends Vehicle.

Now three tables are created

Vehicle
TransportationVehicle
PassengerVehicle

but when I query database using

from Vehicle v

Hibernate issues union query for all the three tables, why it does like this? I am just asking for Vehicle.

4

There are 4 best solutions below

0
Zufar Muhamadeev On

TransportationVehicle and PassengerVehicle are subclasses of Vehicle. Hibernate will return all instances of Vehicle(TransportationVehicle and PassengerVehicle are instances of Vehicle too). If you want to select only Vehicle you could create hierarchy:

AbstractVehicle
Vehicle extends AbstractVehicle
TransportationVehicle extends AbstractVehicle
PassengerVehicle extends AbstractVehicle

AbstractVehicle should be annotated with @MappedSuperclass.

0
kraskixxx On

You may try @Inheritance(strategy=InheritanceType.JOINED) annotation

0
Bilal BBB On

Because TransportationVehicle and PassengerVehicl are also Vehicule. This is how works polymorphic queries in hibernate. If you want a PassengerVehicl you will have only PassengerVehicl.

If you want to get only a Vehicule, you need to change your model.

0
Dragan Bozanovic On

That's the desired behavior and is the core feature of most ORM query languages.

To limit the result to one class of entities:

"from Vehicle v where v.class = " + Vehicle.class.getName();