Spring JpaRepository findBy ...在(Collection)中返回union不交集 [英] Spring JpaRepository findBy...In(Collection) returns union not intersection
问题描述
我在JpaRepository中有一个查询方法
Page< Course> findDistinctCourseByAttrsInAllIgnoreCase(Set< String> a,Pageable page);
通过实例变量找到课程
对象组<字符串> ATTRS
。给定一个带有foo和bar的 a
,我想找到课程
,其中 attrs
包含foo和bar,即 Course
s与foo和那些酒吧。上面的这个方法返回一个联合。
有没有办法使用JpaRepository查询来做到这一点,或者我必须进行多次调用并找到交集?
在不太可能的情况下,您知道 a s的数量,您可以将多个约束与
和:
... AttrsInAndAttrsIn ...
但是,即使前提条件是非常丑陋。
下一个最好的选择可能是一个规范和一个factoryMethod,它可以从
Set
或从可变参数中构造规范>
您的存储库需要扩展
JpaSpecificationExecutor
。
您可以这样称呼它页面<课程> findAll(matchesAll(attrs),pageable)
工厂方法看起来像这样:
规格<课程> MatchAll(Set< String> attrs){
return(Root< T> root,CriteriaQuery<>查询,CriteriaBuilder构建器) - > {
//通过将调用合并到builder.isMember
来构造谓词// https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html#isMember( E,%20javax.persistence.criteria.Expression)
$ b code $ preI have a query method in my JpaRepository
Page<Course> findDistinctCourseByAttrsInAllIgnoreCase(Set<String> a, Pageable page);
to find
Course
objects by their instance variableSet<String> attrs
. Given a Seta
with "foo" and "bar", I want to findCourse
s whoseattrs
contain BOTH "foo" and "bar", i.e. an intersection ofCourse
s with "foo" and those with "bar". This method above returns a union.
Is there a way to do this with JpaRepository queries or do I have to make multiple calls and find the intersection myself?解决方案In the unlikely case that you know the number of
a
s up front you could combine multiple constraints withAnd
:...AttrsInAndAttrsIn...
But even if the precondition holds that would be very ugly.
So the next best option is probably a Specification and a factoryMethod constructing the Specification from a
Set<String>
or from varargs.Your repository needs to extend
JpaSpecificationExecutor
. You would call it like thisPage<Course> findAll(matchesAll(attrs), pageable)
And the factory method would look something like this:
Specification<Course> matchesAll(Set<String> attrs) { return (Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> { // construct Predicate by combining calls to builder.isMember // https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html#isMember(E,%20javax.persistence.criteria.Expression) } }
这篇关于Spring JpaRepository findBy ...在(Collection)中返回union不交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!