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

时间:2017-08-07 20:05:33

标签: 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;
}

和儿童实体:

@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的所有父母。我尝试以这种方式在我的存储库中执行此操作:

@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);

例外:

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编写它?

2 个答案:

答案 0 :(得分:3)

我找到了解决方案:

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

答案 1 :(得分:0)

您实际上根本不需要使用@Query,您可以使用 Spring Data JPA Repositories 中的派生查询方法并通过子属性查找父对象。在您的场景中,存储库中 find 方法的正确名称应该是:

Page<Visit> findByChildId(String id);