gpt4 book ai didi

java - Spring Data Rest JPA 休息服务与 hibernate : control lazy loading

转载 作者:行者123 更新时间:2023-12-02 10:22:55 28 4
gpt4 key购买 nike



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

我有一个如下所示的实体。有时我不需要延迟加载的 jobDocuments,但有时我需要它。我可以编写 2 个剩余方法,一个将返回带有 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 实体,但不要将其用作休息服务响应。创建单独的类来表示 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();
}
}

假设你有这样的 Controller :

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

关于java - Spring Data Rest JPA 休息服务与 hibernate : control lazy loading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191938/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com