【问题标题】:Spring Data JPA - how to fetch parents by child id?Spring Data JPA - 如何通过孩子ID获取父母?
【发布时间】:2018-01-15 05:31:46
【问题描述】:

我有带有 @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怎么写?

【问题讨论】:

  • 您能否解释一下您在使用该@Query 时遇到的错误?此外,您列出的方法返回一个Page&lt;Visit&gt;,您的意思是将其更新为Page&lt;Parent&gt;
  • where p.childs.id = :childId 是非法的 JPQL。如果您想加入Child,请进行显式加入

标签: java spring jpa


【解决方案1】:

我找到了解决办法:

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

【讨论】:

    【解决方案2】:

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

    Page<Visit> findByChildId(String id);
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 2021-03-29
      • 1970-01-01
      • 2018-04-19
      • 2022-11-24
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多