首页 > 解决方案 > Java Spring Data JPA - 在子节点上搜索长实体链以返回整个实体结构

问题描述

我有一个相当长的实体链,如下所示,每一步都是一对多的关系:

Reference -> DocumentVersion -> CodeSet -> Configuration -> Run

我需要在特定日期获得所有运行,但是,我需要返回整个参考实体。

参考.java

@Entity
@Table(name = "reference")
public class Reference {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(updatable = false, nullable = false)
    private int internalNumber;

    @OneToMany(mappedBy = "id")
    private List<DocumentVersion> documentVersion;

    public List<DocumentVersion> getDocumentVersion() {
        return documentVersion;
    }
    public void setDocumentVersion(List<DocumentVersion> documentVersion) {
        this.documentVersion = documentVersion;
    }
}
... -> DocumentVersion -> CodeSet -> Configuration -> ...

运行.java

@Entity
@Table(name = "run")
public class Run {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int runReference;

    @Column(nullable = false)
    private Date runDate;

    @ManyToOne
    @JoinColumn(name="configuration_reference", nullable=false)
    private Configuration configuration;
}

从控制器中,我们在服务中调用此函数:

public Optional<List<Run>> getRunsByDate(String sAnyDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate anyDate = LocalDate.parse(sAnyDate, formatter);
        return runRepo.findByRunDate(anyDate);
    }

返回所有运行。

当我启用时,logging.level.org.hibernate.SQL=debug我可以看到它为整个实体链生成 SQL,有什么方法可以访问该数据并返回,还是有另一种方法让 JPA 简单地返回参考?

标签: javaspring-data-jpa

解决方案


如果我理解正确,您想通过 DocumentVersion -> CodeSet -> Configuration 提取所有相关的引用来运行,对吗?

如果是,您可以使用 ReferenceRepository 和类似的方法来做到这一点

findByDocumentVersion_codeSet_configuration_run_date


推荐阅读