使用QueryDsl / Hibernate进行延迟加载无法正常工作

时间:2016-06-07 13:49:56

标签: java hibernate querydsl

/ **家长实体** /

@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班级*******

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

此外我想有条件地(根据要求)获取儿童记录,我该如何实现?

1 个答案:

答案 0 :(得分:1)

在做了一些研究之后,我在这里找到了必要的工作,

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

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

“此模块支持Hibernate特定数据类型和属性的JSON序列化和反序列化;尤其是延迟加载方面。”通过添加此模块,Jackson不再尝试序列化Lazy Loaded集合。

相关问题