Search code examples
spring-datahibernate-criteriajpa-criteria

JPA Criteria Query - How to join on only a subclass of the association entity type?


I'm using Spring, Hibernate and the JPA Criteria API.

Let's say I have a Vehicle class hierarchy and a Tire class. Each Vehicle can have multiple Tires.

  • Vehicle -- Tanker, Motorcylce

  • Tire

I want to query for small tires that are on Tankers with a capacity over 100 gallons. But the vehicle property for Tire is of type Vehicle. Only one of the Vehicle subclasses (Tanker) has the "capacity" property. How do I tell the criteria api to join ONLY on Tankers?

Thanks!

I'm sure this is has been asked/answered before, but I think I'm missing the right terminology to have a successful search.


Solution

  • Try this:

    @Entity
    public class Vehicle {
        @OneToMany
        private Set<Tire> tires;
    }
    
    @Entity
    public class Tank extends Vehicle {
        private int gallons;
    }
    
    @Entity
    public class Motorcycle extends Vehicle {
    }
    
    @Entity
    public class Tire {
    }
    
    public interface VehicleRepo extends JpaRepository<Vehicle, Long> {
    
        @Query("select v.tires from Vehicle v where v.gallons > ?1")
        List<Tire> findByGallonsIsGreaterThan(int gallons);
    }
    

    If you need select only subclass type in JPQL query you can use this approach:

    select v from Vehicle v where type(v) = Tank
    select v from Vehicle v where v.class = Tank
    

    Example and test.