mysql - 带有可选参数的 JpaRepository

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

我有一个供客户使用的 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") 字符串名称, @Param("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 上却不行。

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

最佳答案

尝试使用正确的格式,例如使用 concat

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

关于mysql - 带有可选参数的 JpaRepository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858239/

相关文章:

java - 在jsp页面中显示mysql数据库的多行

php - 比较mysql中的两个日期

mysql - 如何通过MySQL从表中获取2分钟(年)和计数(标题)?

java - 使用不带"No query defined for that name"的spring-data-jpa时出现"@Query"异常

java - AWS DynamoDBMapper 保存方法不断抛出 `DynamoDBMappingException: not supported; requires @DynamoDBTyped or @DynamoDBTypeConverted`

php - mysqli_num_rows 为 1 但 mysql_fetch_assoc 返回 null

java - 无法写入 JSON : failed to lazily initialize a collection

java - 正则表达式模式可选组取决于空间

java - 无法在 Controller 类中使用组件/服务/存储库

java - Spring REST API 并防止更改自动生成的属性?