如何将可变数量的参数传递给Spring Data / Hibernate / JPQL查询

时间:2017-04-04 20:26:33

标签: java spring hibernate spring-data-jpa jpa-criteria

我需要将一个可变数量的参数传递给spring / JPA repo来模仿这样的东西。

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。我已经google了一下,似乎没有办法用普通的CRUD回购做到这一点,但到目前为止我还没有找到任何看起来像我需要的例子。我认为CriteriaBuilder是我应该使用的,但这似乎已经失宠了,所以我不确定这样做的正确方法是什么。

2 个答案:

答案 0 :(得分:0)

也许你正在寻找这样的东西?:

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def omniauth_providers
    process_oauth(request.env['omniauth.auth'].merge(session.fetch(:user_attributes, {})))
  end

  alias facebook omniauth_providers
  alias github omniauth_providers

  private

  def process_oauth(omniauth_params)
    user = User.from_omniauth(omniauth_params)
    if user.persisted?
      flash.notice = 'Signed in!'
      sign_in_and_redirect user
    else
      session['devise.user_attributes'] = user.attributes
      redirect_to new_user_email_registration_path
    end
  end
end

Source

答案 1 :(得分:0)

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

    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 + "%");
    }

我的回购定义就是这个。

interface InternalProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor