带有可选参数的 JpaRepository

JpaRepository with optional parameters

我有一个 MySQL table 给这样的客户:

name | country | many more columns
----------------------------------
John   USA
null   France
Max    null
null   null
...

在我的应用程序中我想查询这个table。用户可以指定不同的搜索字段,但不必设置每个值。 我在存储库 Class 中组合查询,我想忽略空参数。

例如,几个搜索参数的预期结果:

Name      | Country       Result
--------------------------------
John      | (not set)     first table line
(not set) | (not set)     all entries
(not set) | a             line one and two (case insensitive)

我知道我可以创建如下查询:
findByNameAndByCountry( @Param("name") String name, @Param("country") String country);
但在应用程序中我有七个搜索参数。因为没有必要全部指定,所以有 128 个不同的搜索,我不想实现。

所以我的想法是像这样查询数据库:

public interface CustomerRepository extends JpaRepository<Customer, java.lang.String> {

   @Query("SELECT c FROM customer c WHERE "
          + "(:name = '' OR c.name LIKE %:name%) "
          + "AND (:country = '' OR c.country LIKE %:country%)")
   List<Customer> findByParams(@Param("name") name, @Param("country") country);

}

问题是,这不起作用。如果我只用 LIKE 检查参数,我不会得到预期的结果,因为 '%' != null。但如果搜索参数为空,我也希望数据库条目具有空值。我试图用 :param = '' 检查参数是否为空,但由于某种原因这不起作用。

我还用 IF(:param != '', c.param, '%') LIKE %:param% 测试了每个参数,遗憾的是结果相同。

奇怪的是,如果我直接在我的数据库上尝试这个命令它工作得很好,但 JpaRepository 不行。

有人知道为什么这不起作用。或者对于我的问题有没有更好的解决方案,我没有想到?感谢您的帮助:)

尝试使用适当的 like 格式使用 concat

    "SELECT c FROM customer c WHERE "
      + "(:name = '' OR c.name LIKE concat('%', :name ,'%'') "
      + "AND (:country = '' OR c.country LIKE concat ('%', :country, '%'')"