QueryDsl/Hibernate 的延迟加载不起作用

Lazy Loading with QueryDsl/Hibernate not working

/** 父实体 **/

@Entity

@Table(name = "Parent")

public class Parent {

  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy = IDENTITY)
  @Column(name = "parentId", unique = true, nullable = false)
  private Integer parentId;


  @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")   
  @JsonManagedReference
  private Set<Child> childs = new HashSet<Child>(0);    

}

****** 子实体 ******

@Entity

@Table(name = "Child")

public class Child {

private static final long serialVersionUID = 1L;

  @ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class)
  @JoinColumn(name = "GuestID")
  @JsonBackReference
  private Parent parent;

}

当我尝试检索父详细信息时,它还会获取子记录,这不应该发生,因为我已经提供了 FetchType.LAZY。

*********** DAO Class *******

public class ParentRepositoryImpl implements ParentRepository {

  public final List<Parent> retrieveParentList(){

    QParent qParent = QParent.parent;
    JPQLQuery<Parent> query = new JPAQuery<Parent>(em);
    List<Parent> parents = query.from(qParent).fetch();
  }
}

我还想有条件地(根据要求)获取子记录,我该如何实现?

经过一些研究后,我在下面找到了必要的工作,

实际上,REST API 需要序列化数据并通过网络发送。就我而言,我使用 Jackson 将 Java 对象序列化为 JSON 格式。默认情况下,Jackson ObjectMapper 不了解 Hibernate 及其延迟加载方案。在序列化过程中,Jackson 接触了实体的所有属性,导致 Hibernate 获取所有数据,从而失去了从延迟加载中获得的好处。

为了避免这种情况,我们需要实施 jackson-module-hibernate

"This module support JSON serialization and deserialization of Hibernate specific datatypes and properties; especially lazy-loading aspects." 添加此模块后,Jackson 不再尝试序列化 Lazy Loaded 集合。