我在我的应用程序中使用SpringDataJPA,DB2是数据库,表的设计是不能改变的。
我有以下类。* 帐户 * 类与 * 作业 * 具有一对多关系,作业与 * 任务 * 具有一对多关系。
@Data
@Entity
@Table(name = "ACCOUNT")
public class Account {
@EmbeddedId
private AccountId id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "account_type", referencedColumnName = "ACCOUNT_TYPE")
@JoinColumn(name = "account_number", referencedColumnName = "ACCOUNT_NUMBER")
@JoinColumn(name = "location_code", referencedColumnName = "LOCATION_CODE")
private List<Job> jobs;
// More fields...
}
@Data
@Entity
@Table(name = "ACCOUNT_JOB")
public class Job {
@EmbeddedId
private JobId id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "job_number", referencedColumnName = "JOB_NUMBER")
@JoinColumn(name = "part_number", referencedColumnName = "PART_NUMBER")
@JoinColumn(name = "job_date", referencedColumnName = "JOB_DATE")
@JoinColumn(name = "account_type", referencedColumnName = "ACCOUNT_TYPE")
@JoinColumn(name = "account_number", referencedColumnName = "ACCOUNT_NUMBER")
@JoinColumn(name = "location_code", referencedColumnName = "LOCATION_CODE")
private List<Task> tasks;
}
@Data
@Entity
@Table(name = "JOB_TASK")
public class Task {
@EmbeddedId
private TaskId id;
@Column(name = "AP_PAY_CODE")
private String taskName;
@Column(name = "TASK_STATUS_DATE")
private Date taskStatusDate;
}
我想获取帐户和它的所有作业和相关任务。如果我在关系中提到获取类型EAGER,我就能够通过使用Repository中的 findById 方法传递帐户ID来获取整个数据。但对于许多场景,我只想获取帐户,而其他场景需要在必要时延迟加载。
所以我想到了使用JOIN FETCH
而不是findById来获得所有数据的自定义查询。但是如何将查询写入JOIN FETCH以在子级别上进行连接呢?
@Query("SELECT account FROM Account account JOIN FETCH account.jobs jobs /*WHAT TO ADD HERE*/ where account.id = :accountId")
Optional<Account> getAccountData(@Param("accountId") AccountId accountId);
1条答案
按热度按时间xxe27gdn1#
使用此本机查询获取每个作业及其各自的任务