Spring Data JPA - 如何通过父对象的id找到嵌套对象?

时间:2017-09-24 19:05:02

标签: java spring spring-data spring-data-jpa

一些对象:

public class SomeObject {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "someObject")
    @Cascade(CascadeType.ALL)
    private Collection<NestedObject> nestedObjects;

    // ...
}

嵌套对象:

public class NestedObject {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private SomeObject someObject;

    // ...
}

我可以通过 findAll 方法找到所有嵌套对象,但我找不到 someObject 的id或者自己的嵌套对象(我得到空集合)

public interface NestedObject Repository extends JpaRepository<NestedObject , Long> {

    Collection<NestedObject> findBySomeObject_Id(Long id);

    Collection<NestedObject> findBySomeObject(SomeObject someObject);
}

1 个答案:

答案 0 :(得分:0)

忘记在 SomeObject 的构造函数中 NestedObject 中初始化 SomeObject

    for (NestedObject nestedObject: nestedObjects)
        nestedObject.setSomeObject(this);