JPQL 过滤 child

JPQL Filtering child

我正在使用 spring 数据 jpa: 在 parent 上过滤 child object 的最佳方法是什么? 在我下面的例子中 我想要 Parent objects 有活跃的 childs,也只想要活跃的 childs 作为列表 parent

  @Query(select distinct p from Parent p inner join p.child c where c.active=:active)

    Page<Parent> getAllPArents(@Param("active") int active);

    @Entity
    Parent{  
      @OneToMany(fetch=FetchType.LAZY)
      List<Child> child;
    }

    @Entity
    Child{
      @ManyToOne
      Parent parent;
    }

我花了很多时间,在查询 parent 时找不到任何解决方案来过滤 child。 我决定更改数据库结构,以便能够查询我想要的 child。添加了另一个 filed/property 可以将 child 放入不同的类别。当使用唯一标准查询 child 时,只会给我需要的 child,也给了我我也需要的 parent。

我遇到了完全相同的问题,我花了一段时间才弄清楚这是如何工作的。当您像这样在 JOIN 之后添加 FETCH 时,子列表将被过滤:

SELECT p FROM Parent p JOIN FETCH p.child c WHERE c.active=:active

我找到了这样做的方法: 您可以使用@Where 注释来过滤一对多或多对多关系的子项。

public class Parent {

    @OneToMany(mappedBy="Parent")
    @Where(clause = "active = 1") //In case of a boolean but it can be a LIKE, a comparator...
    private Set<Child> childs; //This gets filled with pets with a name starting with N

    //getters & setters
}