Spring JpaRepository findBy ...在(Collection)中返回union不交集 [英] Spring JpaRepository findBy...In(Collection) returns union not intersection

查看:419
本文介绍了Spring JpaRepository findBy ...在(Collection)中返回union不交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JpaRepository中有一个查询方法

  Page< Course> findDistinctCourseByAttrsInAllIgnoreCase(Set< String> a,Pageable page); 

通过实例变量找到课程对象组<字符串> ATTRS 。给定一个带有foo和bar的 a ,我想找到课程,其中 attrs 包含foobar,即 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 $ pre

I have a query method in my JpaRepository

    Page<Course> findDistinctCourseByAttrsInAllIgnoreCase(Set<String> a, Pageable page);

to find Course objects by their instance variable Set<String> attrs. Given a Set a with "foo" and "bar", I want to find Courses whose attrs contain BOTH "foo" and "bar", i.e. an intersection of Courses 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 as up front you could combine multiple constraints with And:

...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 this

Page<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆