Spring Data Rest JPA rest service with hibernate:控制延迟加载

Spring Data Rest JPA rest service with hibernate: control lazy loading



我想知道是否有一种方法可以使用休息服务方法调用来控制延迟加载和急切加载。让我详细说一下。

我有一个如下所示的实体。有时我不需要延迟加载的 jobDocuments,但有时我需要它。我可以写 2 个休息方法,一个 return 带有 jobDocuments 的 Job 对象,另一个没有?

@Table(name = "JOB")
public class Job implements Serializable {

  @Id
  @Column(name = "JOB_ID", unique = true, nullable = false)
  private Long id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "job")
  @Column(name = "PRINT_JOB_ID", length = 30)
  private JobDocument jobDocuments;

}

我建议你不要混合数据模型和表示(在你的情况下是实体和 http 响应)。

您可以让您的 Job 实体默认延迟加载,但不要将其用作休息服务响应。创建单独的 class 来表示 http 响应并包装来自您的实体的数据。例如:

@Table(name = "JOB")
public class Job implements Serializable {
    @Id
    @Column(name = "JOB_ID", unique = true, nullable = false)
    private Long id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "job")
    @Column(name = "PRINT_JOB_ID", length = 30)
    private JobDocument jobDocuments;
    . . .
}

// your response class, which wrap Job data
public class JobResponse {
    @JsonProperty("id")
    private Long id;
    @JsonProperty("jobDocuments")
    private JobDocument jobDocuments
    . . .
    // use this when you need to have jobDocuments 
    public static JobResponse fromJobWithDocuments(Job job) {
        this.id = job.getId();
        this.jobDocuments = job.getJobDocuments(); // you fetch lazy field, so it would be pre-populated
    }

    // use this when you don't need to have jobDocuments 
    public static JobResponse fromJob(Job job) {
        this.id = job.getId();
    }
}

假设你有这样的控制器:

public class Controller {
    . . .
    public ResponseEntity<JobResponse> getJob(boolean withDocuments, long jobId) {
        JobResponse response;
        Job job = jobService.getJob(jobId); // assuming you are getting job somehow
        if (withDocuments) {
            response = JobResponse.fromJobWithDocuments(job)
        } else {
            response = JobResponse.fromJob(job)
        }
        return new ResponseEntity<JobResponse>(response);
    }
    . . .
}