'JPA direct join to entities with common primary key

Assume I have dozen of one-to-one relation using common id carId and I can't touch schema or merge them into one.

@Entity
public class Car {
  @Id
  private Integer id;

  @OneToOne(mappedBy="car")  
  private Registration regist;

  @OneToOne(mappedBy="car")  
  private Detail detail;

  @OneToOne(mappedBy="car")  
  private License license;
}

@Entity
public class Registration {
  @OneToOne
  private Car car;

  private String governor;
}

@Entity
public class Detail {
  @OneToOne
  private Car car;

  private Date manufacturingDate;
}

@Entity
public class License {
  @OneToOne
  private Car car;

  private String licenseNumber;
}

// and more ...

When I create a query begin with License to get data from Detail and Registration, the generated sql looks like

select
    car_detail.manufacturing_date,
    car_registration.governor
from
    car_license
left outer join
    car
        on car_license.car_id=car.id
left outer join
    car_detail
        on car.id=car_detail.car_id
left outer join
    car
        on car_license.car_id=car.id
left outer join
    car_registration
        on car.id=car_registration.car_id
where
    and car_license.licenseNumber=?

It's reasonable because JPA doesn't understand column car_id is common across entities. However, the result is hard to debug and error prone on complicated join.

How can I define those entities so that JPA knowns they don't need additional join on table car and can be joined directly, or just join to table car only once?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source