Spring Data JPA - 如何通过孩子 ID 获取父母?

Cat*_*t H 7 java spring jpa

我有带有@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;
}
Run Code Online (Sandbox Code Playgroud)

和子实体:

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

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

}
Run Code Online (Sandbox Code Playgroud)

我的任务是查找包含具有特定 ID 的 Child 的所有父母。我尝试以这种方式在我的存储库中执行此操作:

@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);
Run Code Online (Sandbox Code Playgroud)

例外:

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--]
Run Code Online (Sandbox Code Playgroud)

我知道可以解决添加_到方法名称findByChilds_Id(如此)的问题,但我找不到如何在@Query注释中编写它。

如何使用 JPQL 编写它?

Cat*_*t H 4

我找到了解决方案:

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