Spring Data Jpa 在具有一对多关系的子级别中使用JOIN FETCH

dfddblmv  于 2023-03-08  发布在  Spring
关注(0)|答案(1)|浏览(120)

我在我的应用程序中使用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);
xxe27gdn

xxe27gdn1#

使用此本机查询获取每个作业及其各自的任务

@Query(value="select a.jobs,b.tasks from ACCOUNT a join ACCOUNT_JOB b on 
ACCOUNT_TYPE  a.account_type=b.ACCOUNT_TYPE  join JOB_TASK C on 
b.ACCOUNT_TYPE=c.id",nativeQuery=true)

相关问题