2

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.

Jim Ott
  • 725
  • 13
  • 24
  • Hello, if the answer helped you don't forget to accept/upvote it. – Cepr0 Jul 12 '17 at 18:51
  • Sorry. Right after I posted this, I found a workaround and got really busy. Couldn't get back to this until now. I was actually looking for a solution using the criteria query API. However, your solution showed me how I was overlooking the obvious and could apply the same concept to make it work. Thank you. – Jim Ott Jul 27 '17 at 02:53

1 Answers1

0

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.

Cepr0
  • 28,144
  • 8
  • 75
  • 101