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

时间:2015-06-01 10:38:48

标签: java java-ee jpa criteria-api

构建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一对一的关系中?

1 个答案:

答案 0 :(得分:0)

我找到了答案

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

cq.select(entity1root);