简体   繁体   English

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

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

I have a JPA method that finds list of Students by their graduation status. 我有一个JPA方法,根据毕业状态查找学生列表。

List<Student> findAllByStatus(Status status);

But if the request is made with null Status, I want to retrieve entities with null status. 但是如果请求是使用null状态,我想检索具有null状态的实体。

How can I handle this with JPARepository using only one method query, to achieve no filtering by status if the status is null? 如何使用JPARepository只使用一个方法查询来处理这个问题,如果状态为null,则不按状态进行过滤?

Thanks in advance. 提前致谢。

You should use something like: 你应该使用类似的东西:

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

Just a little fix to Ankit Kanani answer. 只是对Ankit Kanani答案的一点修复。

Try 尝试

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

This method involves a bit more code but i think it's your best bet : 这种方法涉及更多的代码,但我认为这是你最好的选择:

@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);
}

The .withIgnoreNullValues() is the key. .withIgnoreNullValues()是关键。 It will just return everything if you send a null value instead of an enum constant. 如果发送空值而不是枚举常量,它将返回所有内容。

JPA is generating SQL statement with equal sign. JPA生成带有等号的SQL语句。 Comparing null with equal sign does not work in most DBMS. 将null与等号进行比较在大多数DBMS中都不起作用。 Instead is keyword is needed: 取而代之的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