java - 子实体通过延迟获取来获取

标签 java hibernate

我在使用 Hibernate Spring 获取数据时遇到问题。我试图找出为什么特定的 Get 请求无法按我的预期工作。

Database lay out

目标是使用以下方法获取表国家/地区中所有国家/地区的列表:

> @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/

相关文章:

java - Hibernate,自动持久化依赖对象

hibernate - 是否可以使用 JPA 从 javax.persistence.Query.getResultList() 流式传输结果?

java - 处理 Android Java 应用程序中的 Drive Rest API 错误

java - Jar 文件 ../android-8/android.jar 没有源代码附件

java - 使用Spring Boot构建kafka生产者失败

java - Hibernate 连接无法在 Apache Tomcat 启动时运行

java - 如何使用 javax.crypto 通过 HTTP header 传递加密的 AES 字符串

Java - 正确处理不同的 JFrame 后 JLabel 损坏

java - hibernate 延迟加载

java - @autowire 注释不起作用