如何使用CriteriaBuilder检查Set中的实体是否包含某个值?
我有以下课程:
@Entity
public class Object {
@ManyToOne
@JoinColumn(name="RelationId", referencedColumnName = "ID", nullable=true)
private Relation relation;
}
@Entity
public class Relation{
@OneToMany(mappedBy="relation")
private Set<Object> objects = new HashSet<>();
@OneToMany(mappedBy="relation")
private Set<Contact> contactpersons = new HashSet<>();
}
@Entity
public class Contact{
@ManyToOne
@JoinColumn(name="RelationId")
private Relation relation;
private Boolean isPrimary;
}
这是我的rootQuery的一些代码:
private Stream<Specification<Object>> toSpec(List<SearchCriteria> searchCriteria){
return searchCriteria.stream().map(criteria ->{
if (criteria.isSet(ObjectKeys.searchObject)) {
return (Specification<Object>) (root, query, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
[Here a criteriabuilder predicate needs to go that check if object has relation that has
contacts that have isPrimary on true]
return criteriaBuilder.or(predicates.toArray(new Predicate[0]));
}
}
}
}
如何使用CriteriaBuilder检查对象关系是否包含isPrimary
on true的联系人
我尝试使用criteriaBuilder.in()
,但它只能检查联系人对象是否在集合中,而不能检查联系人对象是否具有特定值。我也尝试过使用联接,但这并没有给出正确的结果,因为我只能使用左、内或右联接,这会导致重复的对象或不可为空的对象。
SQLJPA
您在这里需要的是关系代数中的所谓半联接,它是通过推荐答案中的EXISTS谓词建模的,在JPA中也受支持。您必须将相关子查询与EXISTS谓词一起使用。大致如下:
private Stream<Specification<Object>> toSpec(List<SearchCriteria> searchCriteria){
return searchCriteria.stream().map(criteria ->{
if (criteria.isSet(ObjectKeys.searchObject)) {
return (Specification<Object>) (root, query, criteriaBuilder) -> {
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Object> correlated = subquery.correlate(root);
Join<?, ?> join = correlated.join("relation").join("contactpersons");
subquery.select(criteriaBuilder.literal(1));
subquery.where(criteriaBuilder.isTrue(join.get("isPrimary")));
return criteriaBuilder.exists(subquery);
}
}
}
}
相关文章