1

我想使用参数表达式作为 in 子句的一部分。我想查询在一组 Bars 中有一个 Bar 的 Foos 列表。这可能吗?

Foo
    // Join, ManyToOne
    Bar getBar()

Query
    ParameterExpression<???> barParameter;

    void setup() {
        CriteriaBuilder builder = ...
        CriteriaQuery<Foo> criteria = ...
        Root<Bar> root = ...

        barParameter = builder.parameter(???);

        criteria.where(
            builder.in(root.get(Foo_.bar)).value(barParameter)
        );
    }

    List<Foo> query(Set<Bar> bars) {
        TypedQuery<Foo> query = createQuery();
        query.setParameter(barParameter, bars);
        return query.getResultList();
    }
4

1 回答 1

8

对于in表达式,您只能使用原始比较类型,因此您需要进行连接并比较原始类型的字段(这里我使用过Integer id):

Root<Foo> foo = cq.from(Foo.class);
Join<Foo, Bar> bar = foo.join(Foo_.bar);
ParameterExpression<Collection> bars = cb.parameter(Collection.class);
cq.where(bar.get(Bar_.id).in(bars));
TypedQuery<Foo> tq = em.createQuery(cq);
Collection<Integer> barsParameter = new ArrayList<Integer> ();
barsParameter.add(1);
List<Foo> resultList = tq.setParameter(bars, barsParameter).getResultList();
于 2012-08-07T17:20:24.897 回答