【问题标题】:How to pass variable number of parameters to Spring Data/Hibernate/JPQL query如何将可变数量的参数传递给 Spring Data/Hibernate/JPQL 查询
【发布时间】:2017-08-30 05:37:24
【问题描述】:

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

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 是我应该使用的,但这似乎已经失宠,所以我不确定这样做的正确方法是什么。

【问题讨论】:

  • 难道只是添加一个带有@Query("SELECT y FROM YourTableEntity y WHERE y.name like '%:param1%' or like y.name like '%:param2%' .... 之类注释的List<YourTableEntity> find(String param1, String param2....) 方法就足够了吗?
  • 如果参数个数未知我会使用Specification<>
  • 你可以像SELECT * FROM Table t WHERE t.col1 LIKE %?1% OR t.col2 LIKE %?2% OR t.col3 LIKE %?3%一样使用JPQL

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


【解决方案1】:

所以我遵循了@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 

【讨论】:

    【解决方案2】:

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

    @Query("select e from Entity e "
          +"where (:field1 = '' or e.field1 like '%:field1%') "
          +"and (:field2 = '' or e.field2 like '%:field2%') "
          //...
          +"and (:fieldN = '' or e.fieldN like '%:fieldN%')"
    Page<Entity> advancedSearch(@Param("field1") String field1,
                               @Param("field2") String field2,
                               //...
                               @Param("fieldN") String fieldN,
                               Pageable page);
    

    Source.

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2019-12-07
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2010-11-06
      相关资源
      最近更新 更多