2016-11-30 93 views
1

我有一个带有属性子项的父类作为一对多关系。正如这个例子构建我认为一个孩子只能有一个父:-)我可以使用JPA根据子女数量筛选父项

public class Parent { 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(updatable = false, nullable = false, insertable = false, unique = true) 
private Long id; 

private String name; 

@OneToMany(mappedBy = "parent")  
private Set<Child> children; 

} 

public class Child { 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
@Column(updatable = false, nullable = false, insertable = false, unique = true) 
private Long id; 


private String name; 

@ManyToOne 
private Parent parent; 

} 

但现在我想只筛选有例如2个孩子的父母。 我可以用什么JPA功能来实现这个功能?

一位同事建议为父母添加一个childrenCounter。但我不喜欢这种可能性,因为每次我在父母和/或孩子网站上更改某些内容时,我都必须更新此计数器。

+0

根据您的数据库的大小,您可以过滤使用'streams'(如:'resultSet.streams.filter(P - > p.children.size == 2)') 。以防万一它返回一个小列表。 – Tom

回答

2

很简单。您需要以下JPQL查询:

select p 
from Parent p 
where size(p.children) = 2