【问题标题】:JpaRepository with optional parameters带有可选参数的 JpaRepository
【发布时间】:2016-10-17 21:57:07
【问题描述】:

我有一个 MySQL 表供这样的客户使用:

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

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

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

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。

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

【问题讨论】:

  • 不要使用查询注释来做到这一点。定义自定义存储库实现,并使用 Criteria API 或 QueryDSL 根据参数动态组合查询。
  • 谢谢,我会考虑你的观点。

标签: mysql spring-data-jpa spring-data jpql


【解决方案1】:

尝试使用 concat 的适当格式

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2017-03-28
    相关资源
    最近更新 更多