2017-04-04 104 views
0

我需要将可变数量的参数传递给spring/JPA回购以模仿这种情况。如何将可变数量的参数传递给Spring Data/Hibernate/JPQL查询

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

+0

不会是只需添加一个'列表找到(字符串参数1,字符串参数2 ....)'方法与像'@Query注释(“选择y的YourTableEntityý其中y。像'%:param1%'这样的名字或像'%:param2%'这样的y.name ....'是否足够? –

+1

如果参数的数目是未知的,我会使用[Specification <>](https:// docs –

+0

您可以像使用JPQL一样使用'SELECT * FROM Table t WHERE t.col1 LIKE%?1%OR t.col2 LIKE% ?2%或t.col3 LIKE%?3%' –

回答

0

也许您正在寻找这样的事情?:

@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

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 
相关问题