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?
I found the solution:
@Query("select p from Parent p join p.childs c where c.id = : childId and --some other conditions--")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With