Using a ParameterExpression as part of the In clause

烈酒焚心 提交于 2019-12-31 04:10:16

问题


I would like to use a parameter expression as part of an in clause. I would like to query for a list of Foos that have a Bar that is in a set of Bars. Is this possible?

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

回答1:


With in expressions you can only use primitive comparison types, so you need to make a join and compare a field of a primitive type (here I have used 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();


来源:https://stackoverflow.com/questions/11845925/using-a-parameterexpression-as-part-of-the-in-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!