简体   繁体   中英

JPA Criteria Api - Not in relation entities query

I have a problem with building CriteriaQuery, to check not mapped entity in this relation.

@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 code:

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);
}

criteria fails on validating. How can i build CriteriaQuery, without appending Entity2 to Entity1 in one to one relation?

I found the answer

That line helps mapping objects in query.

cq.select(entity1root);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM