我在使用 Hibernate Spring 获取数据时遇到问题。我试图找出为什么特定的 Get 请求无法按我的预期工作。
目标是使用以下方法获取表国家/地区中所有国家/地区的列表:
> @GetMapping("/getCountry") public List <Country> getCountry(){
> return(List<Country>) countryRepo.findAll(); }
国家实体是:
@Entity
public class Country {
@Id
private Integer id;
private String name;
@OneToMany(mappedBy="country", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JsonManagedReference
private List<PortOfLoading> portOfLoadings;
public Country() {
}
//getters and setters omitted
装货港实体是:
@Entity
公共(public)类PortOfLoading {
@Id
private int id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
private Country country;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "port_of_loading_id", referencedColumnName = "id")
private List<Container> containers;
public PortOfLoading() {
} //getters and setters are omitted
我希望 hibernate 能够进行如下查询:
Hibernate: select country0_.id as id1_4_, country0_.name as name2_4_ from country country0_
但相反,hibernate 开始获取该实体的所有加载端口,之后还获取每个加载端口的所有容器:
Hibernate: select portofload0_.country_id as country_3_5_0_, portofload0_.id as id1_5_0_, portofload0_.id as id1_5_1_, portofload0_.country_id as country_3_5_1_, portofload0_.name as name2_5_1_ from port_of_loading portofload0_ where portofload0_.country_id=?
Hibernate: select containers0_.port_of_loading_id as port_of_8_2_0_, containers0_.id as id1_2_0_, containers0_.id as id1_2_1_, containers0_.carrier_id as carrier_5_2_1_, containers0_.container_reference as containe2_2_1_, containers0_.container_sort_id as containe6_2_1_, containers0_.port_of_loading_country_id as port_of_7_2_1_, containers0_.ocean_freight_costs_invoiced as ocean_fr3_2_1_, containers0_.port_of_loading_id as port_of_8_2_1_, containers0_.terminal_handeling_costs_invoiced as terminal4_2_1_ from container containers0_ where containers0_.port_of_loading_id=?
由于所有其他查询,获取数据需要很长时间,我一直在努力找出原因。
提前致谢!
最佳答案
解决了!函数 FindAll() 使用正确的查询获取所有数据。但是 getCountry() 方法上的 return 语句会获取所有其他实体。添加@JsonIgnore解决了return语句的问题:
@OneToMany(mappedBy="country", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JsonIgnore
private List<PortOfLoading> portOfLoadings;
关于java - 子实体通过延迟获取来获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244961/