如何使用 criteriaBuilder 检查集合中的实体是否包含某个值?

How to check if entity in set contains a certain value using criteriaBuilder?

我有以下 类:

@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 为真

我尝试使用 criteriaBuilder.in(),但它只能检查联系人对象是否在集合中,而不能检查联系人对象是否具有特定值。我也尝试过使用联接来执行此操作,但这并没有给我正确的结果,因为我只能使用左联接、内联接或右联接,这会导致重复对象或不可空对象。

您在这里想要的是关系代数中所谓的半连接,它通过 SQL 中的 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);
            }
        }
   }    
}