gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:34:35 25 4
gpt4 key购买 nike

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

    @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 辆车(我选择了哪个 Id)

所以当我从 Country 加入 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 是懒惰的。你怎么看?

最佳答案

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

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()

关于java - 从 JPA 嵌套的 OneToMany 关系中获取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45185886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com