【问题标题】:Lazy Loading with QueryDsl/Hibernate not working使用 QueryDsl/Hibernate 的延迟加载不起作用
【发布时间】:2016-06-07 13:49:56
【问题描述】:

/** 父实体**/

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

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

【问题讨论】:

    标签: java hibernate querydsl


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多