Spring JPA data - how to get parents by child id?

I have parent and child objects annotated with @ManyToMany:

@Entity
@Table(name = "parent")
public class Parent {

    @Id
    @GenericGenerator(name = "uuid-gen", strategy = "uuid2")
    @GeneratedValue(generator = "uuid-gen",strategy=GenerationType.IDENTITY)
    private String id;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "parents_childs",
        joinColumns = {@JoinColumn(name = "parent_id", nullable = false, updatable = false)},
        inverseJoinColumns = {@JoinColumn(name = "child_id", nullable = false, updatable = false)})
    private List<Child> childs;
}

      

And the child object:

@Entity
@Table(name="child")
public class Child {

    @Id
    @GenericGenerator(name = "uuid-gen", strategy = "uuid2")
    @GeneratedValue(generator = "uuid-gen",strategy=GenerationType.IDENTITY)
    private String id;

}

      

My task is to find all parents that contain a Child with a specific ID. I tried to do it in my repository this way:

@Query("select p from Parent p where p.childs.id = :childId and --some other conditions--")
@RestResource(path = "findByChildId")
Page<Visit> findByChild(@Param("childId") final String childId, final Pageable pageable);

      

An exception:

java.lang.IllegalArgumentException: org.hibernate.QueryException: illegal attempt to dereference collection [parent0_.id.childs] with element property reference [id] [select p from Parent p where p.childs.id = :childId and --some other conditions--]

      

I know it is possible to decide to add _

to the method name, for example findByChilds_Id

(like here ), but I cannot find how to write this to the @Query

annotation.

How do I write it using JPQL?

+3


source to share


1 answer


I found a solution:



@Query("select p from Parent p join p.childs c where c.id = : childId and  --some other conditions--")

      

+2


source







All Articles