【问题标题】:How to handle all enum value in JPA Query method for empty parameter如何在 JPA Query 方法中处理空参数的所有枚举值
【发布时间】:2019-07-12 22:03:29
【问题描述】:

我有一个 JPA 方法,可以根据学生的毕业状态查找学生列表。

List<Student> findAllByStatus(Status status);

但是如果请求是用 null 状态发出的,我想检索具有 null 状态的实体。

如何使用 JPARepository 仅使用一种方法查询来处理此问题,以在状态为 null 时实现不按状态过滤?

提前致谢。

【问题讨论】:

  • 已经提供了一个 findAll 方法,如果状态为 null 则调用它。

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


【解决方案1】:

试试

@Query("SELECT s from Student s WHERE (s.status is null or s.status =?1)")
List<Student> findAllByStatus(Status status);

【讨论】:

    【解决方案2】:

    此方法涉及更多代码,但我认为这是您最好的选择:

    @Override
    public List<Interface> findAllWithFilters(String name, InterfaceType type, String ip) 
    {
        Interface intfc = new Interface();
        intfc.setName(name);
        intfc.setType(type);
        intfc.setIp(ip);
    
        ExampleMatcher matcher = ExampleMatcher.matching()
            .withMatcher("name", match -> match.contains())
            .withMatcher("type", match -> match.exact())
            .withMatcher("ip", match -> match.contains())
            .withIgnorePaths("id", "uuid")
            .withIgnoreNullValues();
        Example<Interface> example = Example.of(intfc, matcher);
    
        return ((InterfaceRepository) baseRepository).findAll(example);
    }
    

    .withIgnoreNullValues() 是关键。如果您发送空值而不是枚举常量,它将只返回所有内容。

    【讨论】:

      【解决方案3】:

      JPA 正在生成带有等号的 SQL 语句。将 null 与等号进行比较在大多数 DBMS 中不起作用。取而代之的是 is 关键字:

      WHERE (s.status =?1 and ?1 is not null) or (s.status is null and ?1 is null)
      

      【讨论】:

        【解决方案4】:

        你应该使用类似的东西:

        @Query("SELECT s from Student s WHERE (?1 is null or s.status = ?1)")
        List<Student> findAllByStatus(Status status);
        

        对 Ankit Kanani 的回答稍作修正。

        【讨论】:

          猜你喜欢
          • 2018-03-19
          • 2019-03-12
          • 2021-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多