通过嵌套对象ID(嵌套两次)查找Spring Data JPA

时间:2019-06-02 18:54:38

标签: spring hibernate jpa spring-data-jpa

有可能吗?

我想使用JPARepository获得具有特定CCC.incidentAssessmentmentId ID的所有AAA对象。有可能吗?

   @Entity
    @Table(schema = "aaa", name = "table")
    public class AAA {

        @Column(name = "kryterium")
        private String criterion;

        @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
        @JoinColumn(name = "id_kryterium_naruszen")
        private List<BBB> violationFactors;

    }

    public class BBB {

        @Column(name = "czynnik")
        private String factor;

        @Column(name = "stopien")
        private float degree;

        @JsonManagedReference
        @OneToOne(mappedBy = "violationFactor")
        private CCC incidentAssessmentFactor;
}

public class CCC {

    @Column(name="komentarz")
    private String comment;

    @Column(name="ocena_naruszenia_wynik_id", updatable=false, insertable=false)
    private Long incidentAssessmentResultId; //-> I'd like to find AAA objects with a specific incidentAssessmentResultId ID

    @Column(name="czynnik_wybrany")
    private Boolean factorIsSelected;

    @Column(name = "wartosc_wybrana")
    private float value;


    @Repository
    public interface ViolationCriterionRepository extends JpaRepository<AAA, Long> {

    //  @Query("select vc from AAA vc left join vc.violationFactors vf left join vf.incidentAssessmentFactor iaf where iaf.incidentAssessmentResultId = ?1")
        List<AAA> findByViolationFactors_IncidentAssessmentFactor_IncidentAssessmentResultId(Long incidentId);
    }

现在,当我调用ViolationCriterionRepository .findAll()时,我获得了所有数据,但是我想获得所有数据,但带有某些CCC对象。我已经尝试使用我的存储库中的以下方法,但得到0个结果。

更新

我的仓库:

@Repository
public interface ViolationCriterionRepository extends JpaRepository<ViolationCriterion, Long> {

    @Query("select vc from AAA vc join vc.violationFactors vf join vf.incidentAssessmentFactor iaf where iaf.incidentAssessmentResultId = ?1")
    List<AAA> findByIncidentAssessmentResultId(Long incidentId);
}

2 个答案:

答案 0 :(得分:1)

在AAAJpaRepository中:

List<AAA> aaaList = findByViolationFactorsIncidentAssessmentFactorIncidentAssessmentResultId( long incidentAssessmentResultId);

答案 1 :(得分:0)

答案是(@JB Nizet-非常感谢!):

@Repository
public interface ViolationCriterionRepository extends JpaRepository<ViolationCriterion, Long> {

    @Query("select vc from AAA vc join vc.violationFactors vf join vf.incidentAssessmentFactor iaf join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
    List<ViolationCriterion> findIncidentAssessmentByIncidentAssessmentId(Long incidentId);
}