我有带有@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;
}
和子实体:
@Entity
@Table(name="child")
public class Child {
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen",strategy=GenerationType.IDENTITY)
private String id;
}
我的任务是找到所有包含具有特定 id 的 Child 的 Parents。我尝试以这种方式在我的存储库中执行此操作:
@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--]
我知道可以解决将 _
添加到方法名称,如 findByChilds_Id
(如 here ),但我找不到如何在 @Query
注解。
如何用JPQL来写?
最佳答案
我找到了解决方案:
@Query("select p from Parent p join p.childs c where c.id = : childId and --some other conditions--")
关于java - Spring Data JPA - 如何通过 child ID 获取 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45554882/