CriteriaBuilder API。 IN子句查询

时间:2018-09-18 07:16:15

标签: java jpa jpa-2.0 criteria criteria-api

有一个数据库架构,如下所示。 enter image description here

我从Collection<String> sportCodes表中收集了codes的集合sport

我可以建立一个谓词...

private Collection<String> sportCodes;

private Predicate searchBySportsPredicate(Root<PlaygroundEntity> root) {
    return root.join(PlaygroundEntity_.specializations).get(SportEntity_.code).in(sportCodes);
}

...并获得PlaygroundEntitysport codes集合中包含的sportCodes集。

反之亦然怎么办?

即建立这样的谓词...

(sportCodes).in(root.join(PlaygroundEntity_.specializations).get(SportEntity_.code))

...并获得带有一组PlaygroundEntity的{​​{1}},其中包括集合sport codes

我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我在此问题上花了3天的时间,解决方案太简单了:

private Predicate searchBySportsPredicate(Root<PlaygroundEntity> root, CriteriaBuilder cb) {
    Collection<Predicate> predicates = new ArrayList<>();
    for (String sportCode : sportCodes) {
        predicates.add(
                cb.equal(root.join(PlaygroundEntity_.specializations).get(SportEntity_.code), sportCode)
        );
    }
    return cb.and(predicates.toArray(new Predicate[0]));
}

重要

它不起作用:

private Predicate searchBySportsPredicate(Root<PlaygroundEntity> root, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>(sportCodes.size());
    Path<String> codePath = root.join(PlaygroundEntity_.specializations).get(SportEntity_.code)
    for (String sportCode : sportCodes) {
        predicates.add(cb.equal(codePath, sportCode));
    }
    return cb.and(predicates.toArray(new Predicate[0]));
}

希望它可以帮助某人。