Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

jpa

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?

like image 716
Oleksandr H Avatar asked Aug 07 '17 20:08

Oleksandr H


1 Answers

I found the solution:

@Query("select p from Parent p join p.childs c where c.id = : childId and  --some other conditions--")
like image 169
Oleksandr H Avatar answered Sep 29 '22 08:09

Oleksandr H