简体   繁体   中英

Spring Data JPA - How to find nested objects by parental object's id?

Some object:

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

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

    // ...
}

Nested object:

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

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

    // ...
}

I can find all nested objects by findAll method, but I can't find nested objects by someObject 's id or itself (I'm getting empty collection).

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

    Collection<NestedObject> findBySomeObject_Id(Long id);

    Collection<NestedObject> findBySomeObject(SomeObject someObject);
}

Forget initialize SomeObject in NestedObject s in SomeObject 's constructor:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM