在JPA2中使用SetJoin

时间:2012-03-30 11:58:02

标签: jpa-2.0

如何使用JPA2 CriteriaBuilder编写下面的sql?

select p from parent p, child c where c.parent_id=p.id and c.code='222' and c.type='SD';

我尝试使用SetJoin,但无法确定如何使用。

提前致谢

2 个答案:

答案 0 :(得分:0)

与您的查询匹配的一种替代方法:

public void foo() {
    // select p from parent p, child c where c.parent_id=p.id and c.code='222' and c.type='SD';
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery <Parent> query = cb.createQuery(Parent.class);

    Root <Parent> r1 = query.from(Parent.class);
    Root <Child> r2 = query.from(Child.class);

    Predicate[] predicates = new Predicate[] {
        cb.equal(r1.get(Parent_.id), r2.get(Child_.parentId)),
        cb.equal(r2.get(Child_.code), "222"),
        cb.equal(r2.get(Child_.type, "SD"))
    };

    query.select(r1);
    query.where(predicates);

    List <Parent> result = entityManager.createQuery(query).getResultList();
}

有很多种方法可以做你想要的,但由于我对你的模型一无所知,除了上面的例子之外,很难给出一个合适的例子。

如果父母与子女相关联,您也可以执行以下操作:

public void foo() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery <Parent> query = cb.createQuery(Parent.class);

    Root <Child> child = query.from(Child.class);
    Join <Child, Parent> parent = child.join(Child_.parent);

    Predicate[] predicates = new Predicate[] {
        cb.equal(child.get(Child_.code), "222"),
        cb.equal(child.get(Child_.type, "SD"))
    };

    query.select(parent);
    query.where(predicates);

    List <Parent> result = entityManager.createQuery(query).getResultList();
}

但这是基于很多假设。

答案 1 :(得分:0)

感谢@Magnus提供详细信息,我解决了我的问题如下:

predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.join("children", JoinType.INNER).get("code"), location.getCode()));
相关问题