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

时间:2017-07-19 09:07:24

标签: java hibernate jpa jpql querydsl

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

    @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个Empoyee,其中1辆车(我选择的ID)

所以,当我从国家开始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 -

我认为这是因为从汽车到员工的ManyToOne是懒惰的。你觉得怎么样?

2 个答案:

答案 0 :(得分:2)

如果所有关系都是双向的,那么我建议从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

答案 1 :(得分:2)

只需选择您想要的其他实体:

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 = ?

或者,由于您的关联是双向的,因此选择汽车:它将为其员工提供一个ManyToOne,其中包含一个ManyToOne及其城市,其中包含ManyToOne及其国家/地区:

select car from Car car where car.id = ?

或只是

em.find(Car.class, carId);

现在你可以做到

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