繁体   English   中英

如何在JPA Query方法中处理空参数的所有枚举值

[英]How to handle all enum value in JPA Query method for empty parameter

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

List<Student> findAllByStatus(Status status);

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

如何使用JPARepository只使用一个方法查询来处理这个问题,如果状态为null,则不按状态进行过滤?

提前致谢。

你应该使用类似的东西:

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

只是对Ankit Kanani答案的一点修复。

尝试

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

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

@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()是关键。 如果发送空值而不是枚举常量,它将返回所有内容。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM