如何将可变数量的参数传递给Spring Data / Hibernate / JPQL查询 [英] How to pass variable number of parameters to Spring Data/Hibernate/JPQL query

查看:456
本文介绍了如何将可变数量的参数传递给Spring Data / Hibernate / JPQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I need to pass in a variable number of parameters to a spring/JPA repo to mimick something like this.

我需要将可变数量的参数传递给spring / JPA库。 * from myTable
其中名称为'%SOME_VALUE%'
或名称为'%SOME_VHERE%''
或名称为'%SOME_OTHER_VALUE2%'
或未知数量的其他值

select * from myTable where name like '%SOME_VALUE%' or name like '%SOME_OTHER_VALUE%' or name like '%SOME_OTHER_VALUE2%' or an unknown number of other values

到目前为止,我还无法确定正确的做法。我使用Spring 4.3.7,Hibernate 5.2.9和Spring Data 1.11.1。我搜索了一下,似乎没有办法通过正常的CRUD回购来做到这一点,但到目前为止,我还没有找到任何看起来像我需要的例子。我认为 CriteriaBuilder 是我应该使用的,但是这似乎已经不受欢迎,所以我不确定正确的方法是什么。 / p>

So far I haven't been able to determine what the correct way to to do this is. I'm using Spring 4.3.7, Hibernate 5.2.9, and Spring Data 1.11.1. I've googled around and it doesn't appear that there's way to do this with a normal CRUD repo, but so far I haven't found any examples that look like what I need. I think CriteriaBuilder is what I am supposed to use, but that seems to have fallen out of favor, so I'm not sure what the correct way to do this is.

推荐答案

所以我遵循@Jorge Campos的建议和使用规范。我的代码现在看起来像这样:

So I followed @Jorge Campos advice and used specification. My code looks like this now:

    public Stream<Product> findProductsContainingDesc(Collection<String> withDesc) {
        Specifications<Product> specifications = null;
        for (String s : withDesc) {
            if(specifications == null){
                specifications = where(hasDescriptionLike(s));
            }else{
                specifications = specifications.or(hasDescriptionLike(s));
            }
        }
        return internalProductRepository.findAll(specifications).stream();
    }

    public static Specification<Product> hasDescriptionLike(String desc) {
        return (root, query, builder) -> builder.like(root.get("description"), "%" + desc + "%");
    }

我的回购定义就是这样。

And my repo definition is this.

interface InternalProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor 

这篇关于如何将可变数量的参数传递给Spring Data / Hibernate / JPQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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