Oleksandr H
Oleksandr H

Reputation: 3015

Spring Data JPA - how to fetch parents by child id?

I have Parent and Child entities with @ManyToMany annotation:

@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 Child entity:

@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 contains Child with a specific id. I tried to do this 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);

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 that it's possible to solve adding _ to method name like findByChilds_Id (as here) but I can't find how to write this in @Query annotation.

How to write it using JPQL?

Upvotes: 9

Views: 14283

Answers (2)

mhsallam
mhsallam

Reputation: 245

You don't actually need to use @Query at all, you can use Derived Query Methods in Spring Data JPA Repositories and find the parent object by a child property. In your scenario the proper name of the find method in the repository should be:

Page<Visit> findByChildId(String id);

Upvotes: 1

Oleksandr H
Oleksandr H

Reputation: 3015

I found the solution:

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

Upvotes: 5

Related Questions