使用QueryDsl/Hibernate进行的延迟加载不起作用 [英] Lazy Loading with QueryDsl/Hibernate not working

查看:132
本文介绍了使用QueryDsl/Hibernate进行的延迟加载不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/**父实体**/

@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);    

}

******儿童实体******

****** The Child Entity ******

@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类*******

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

我也想有条件(应要求)获取子记录,我该如何实现呢?

推荐答案

做完一些研究后,我发现下面的必要工作,

After doing some study i found the necessary work around below here,

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

Actually, REST API needs to serialize data and send it across the wire. In my case, I'm using Jackson to serialize Java objects into JSON format. By default, the Jackson ObjectMapper has no awareness of Hibernate and it's Lazy Loading scheme. During the serialization process, Jackson was touching all the properties on the entity which resulted in Hibernate fetching all the data thereby losing the benefits gained from Lazy Loading.

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

To avoid this we need to implement jackson-module-hibernate.

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

"This module support JSON serialization and deserialization of Hibernate specific datatypes and properties; especially lazy-loading aspects." With the addition of this module, Jackson no longer tries to serialize Lazy Loaded collections.

这篇关于使用QueryDsl/Hibernate进行的延迟加载不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆