【问题标题】:Spring Rest Data projection @OneToOne property not loadingSpring Rest Data 投影@OneToOne 属性未加载
【发布时间】:2018-04-30 21:47:37
【问题描述】:

我有这三个类:

@Entity
public class Trip {

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<Leg> legs;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<TripDetail> details;

  /* snip */
}

@Entity
public class TripDetail {

  @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private CustomComponents customComponents;

  /* snip */
}


@Entity
public class CustomComponents {

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<CustomComponent> existingComponents;

  /* snip */
}

还有这个投影:

@Projection(name = "withUsages", types = { Trip.class })
public interface TripWithUsagesProjection {
  List<LegWithUsagesProjection> getLegs();

  List<TripDetail> getDetails();
} 

现在,当我使用投影对旅行 API 执行 GET 时,返回的 JSOn 中 TripDetail 中的 customComponents 对象为空。

如果我将 TripDetail 中的 customComponents 属性更改为快速加载 (fetch=FetchType.EAGER),那么生成的 JSON 是正确的(因为它包含 customComponents 的内联数据)。

我想知道为什么会这样?

为简洁起见,TripDetail 有许多其他属性未显示(一些 @OneToMany、一些 BigDecimal、字符串和其他属性)。这是唯一的@OneToOne。为什么 @OneToOne 在这里表现不同?

【问题讨论】:

    标签: hibernate spring-rest spring-projections


    【解决方案1】:

    看这段代码

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private CustomComponents customComponents;
    

    您告诉 Hibernate 以 LAZY 方式加载 CustomComponents。即它只会在需要时加载其详细信息。

    因此,如果您正在调试并查找 customComponents,它将为空。

    但是,当您尝试从 CustomComponents 读取一些数据时,它应该会加载 customComponents 详细信息。

    因为 Hibernate 会在后台触发另一个查询

    select * from CustomComponents where id = ?
    

    这就是 LAZY 的工作原理

    更多详情here

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 2015-04-19
      • 1970-01-01
      • 2018-04-18
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      相关资源
      最近更新 更多