从 JPA 嵌套的 OneToMany 关系中获取单个元素

Get single element from JPA nested OneToMany relationship

我有那些实体,它不是来自真实代码,但我认为这并不重要。

    @Entity
    public class Country{

       private String name;
       //other fields with getters and setters
       @OneToMany
       private List<City> cites;


    }

    @Entity
    public class City {

       private String name;
        //other fields with getters and setters
       @OneToMany
       private List<Employee> emps;//list size could be millions


    }

     @Entity
     public class Employee {

        private String name;
        //other fields with getters and setters

       @OneToMany
       private List<Cars> cars;// list size could be 1000

    }


     @Entity
    public class Car {
      private String name;

      @ManyToOne
      private Employee emp;
    }

我想获得单个 Car 实体,但也想获得其他数据(国家、城市、员工),就像这样

1 个国家/地区 1 个城市/1 个员工/1 辆汽车(我将其放在 select)

所以当我从像

这样的国家加入 jpa 时
select c from Country c 
 inner join c.cites ci 
 inner join ci.emps em
  inner join ci.cars car where car.id = ?

我得到了国家(包括所有城市)的所有数据。

我应该怎么做才能获得 1 个国家、1 个城市、1 个员工、1 辆汽车。

如果用一个 jpa 查询不可能做到这一点,请提出其他方法。

所有的关系都是双向的和惰性的。

I tried this way. 
1)select car by id. then get Id of employee from car. 
2)select Employee by id - but at this point Employee data are nulls -

我认为是因为从 Car 到 Employee 的 ManyToOne 很懒。你怎么看?

如果所有关系都是双向的,那么我建议从 Car 开始,然后获取层次结构。

select c from Car car 
  inner join fetch car.emp emp
  inner join fetch emp.city city
  inner join fetch city.country country 
where car.id = ?

请记住在您错过的所有连接中添加 fetch

只是 select 您想要的其他实体:

select c, ci, em, car from Country c 
inner join c.cites ci 
inner join ci.emps em
inner join ci.cars car where car.id = ?

或者,由于您的关联是双向的,select 汽车:它的员工将有一个 ManyToOne,它的城市将有一个 ManyToOne,它的国家将有一个 ManyToOne:

select car from Car car where car.id = ?

或者干脆

em.find(Car.class, carId);

现在你可以做

car.getEmployee().getCity().getCountry()