Java JPA Hibernate:如何限制自引用实体的获取深度

Java JPA Hibernate:如何限制自引用实体的获取深度,java,hibernate,jpa,spring-boot,Java,Hibernate,Jpa,Spring Boot,为了降低复杂性,我将编写一个示例: Human.java @Entity @Table(name = "human") @DynamicInsert(value = true) @DynamicUpdate(value = true) public class Human { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = fals

为了降低复杂性,我将编写一个示例:


Human.java

@Entity
@Table(name = "human")
@DynamicInsert(value = true)
@DynamicUpdate(value = true)
public class Human {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, name = "name")
    private String name;

    @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private Human parent;

    @OneToMany(fetch=FetchType.LAZY, mappedBy ="parent")
    private Collection<Human> children;

    // getters and setters ...
}

数据库:

ID | Name | Parent
1  | Mike | null
2  | John | 1
3  | Bill | 2
4  | Carl | 3

问题:当我为迈克找孩子的时候,我希望在那里只见到约翰,但我得到了卡尔的所有参考资料

如何限制此自引用实体的深度,使其不会超过指定的数字限制

我按照以下步骤构建实体(步骤3)


更新:我发现有人得了a,但他也没有解决。

我的临时解决方案是放弃“儿童”领域。每次调用HumanDao.getChildren(),我都会得到一个Human数组。Hibernate不是获取其他子对象的那个。如果您的问题与您链接的问题类似,那么是您的JSON封送器序列化了人员,从而调用getChildren(),从而延迟加载子项,对其进行封送,从而调用其getChildren()方法,等等。因此,解决方案是配置JSON封送器(如果是Jackson,请使用JsonIgnore,或者使用hibernate模块并将其配置为不封送未初始化的代理,或者将实体转换为适合JSON封送的DTO。这是一个基本示例,这就是为什么它看起来不专业的原因。在有机会封送子字段之前,我正在使用调试器检查这些子字段,它们是已经存在。我还可以看到正在使用
spring.jpa.show sql=true
进行多个查询。使用调试器查看子项也会使Hibernate延迟加载子项。是否确实在编组Himan之前记录了正在记录的sql查询?如果在执行之后放置断点会发生什么重新定义查询,并查看此时记录了多少查询?如果JsonIgnore子项会发生什么?还有,为什么要使用本机查询而不是JPQL查询?我需要一个快速修复,因此我不再记得当时的情况。我已经放弃了第一条评论中所述的子项字段。我也不知道是什么@Query注释应该得到参数。我读过的所有示例都使用该参数。
public class TestClass {

    @Autowired
    private HumanDao dao;

    public void test(Long parentId) {
        Iterable<Human> children = dao.getChildren(parentId);
        System.out.println(children);
    }
}
spring.datasource.url=jdbc:mysql://localhost/db
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.max_fetch_depth=1
ID | Name | Parent
1  | Mike | null
2  | John | 1
3  | Bill | 2
4  | Carl | 3