我有带有@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 编写它?
我找到了解决方案:
@Query("select p from Parent p join p.childs c where c.id = : childId and --some other conditions--")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7546 次 |
最近记录: |