JPA 条件 Api - 不在关系实体查询中

JPA Criteria Api - Not in relation entities query

我在构建 CriteriaQuery 时遇到问题,无法检查此关系中未映射的实体。

@Entity
@Table(name="table1")
public class Entity1 {

    //Some attributes

    @Column
    private Integer entity2ID;

}

@Entity
@Table(name="table2")
public class Entity2 {

    private Integer id;

    //Some attributes

    @Column
    private Boolean value;

}

CriteriaBuilder 代码:

public Query buildSelectQuery(EntityManager em, Criteria c) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    ConcreteCriteria criteria = (ConcreteCriteria) c;

    CriteriaQuery<Entity1> cq = cb.createQuery(Entity1.class);
    Root<Entity1> entity1root = cq.from(Entity1.class);

    List<Predicate> predicates = buildPredicatesList(cb, entity1root, criteria); //other criteria in Entity1

    if (criteria.isValueIsNull() != null) {
        Root<Entity2> entity2root = cq.from(Entity2.class);
        predicates.add(cb.equal(entity1root.get("entity2ID"), entity2root.get("id")));
        predicates.add((criteria.isValueIsNull() ? cb.isNull(entity2root.get("value")) : cb.isNotNull(entity2root.get("value"))));
    }

    cq.where(predicates.toArray(new Predicate[predicates.size()]));

    return em.createQuery(cq);
}

条件验证失败。我如何构建 CriteriaQuery,而不以一对一的关系将 Entity2 附加到 Entity1

我找到了答案

该行有助于映射查询中的对象。

cq.select(entity1root);