Java 如何在JPA查询方法中处理空参数的所有枚举值
我有一个JPA方法,可以根据学生的毕业状态查找学生列表Java 如何在JPA查询方法中处理空参数的所有枚举值,java,hibernate,jpa,spring-data-jpa,spring-data,Java,Hibernate,Jpa,Spring Data Jpa,Spring Data,我有一个JPA方法,可以根据学生的毕业状态查找学生列表 List<Student> findAllByStatus(Status status); 列出findAllByStatus(状态); 但是,如果请求的状态为null,那么我希望检索状态为null的实体 如果状态为null,如何使用JPARepository仅使用一个方法查询来实现不按状态过滤 提前谢谢。试试看 @Query("SELECT s from Student s WHERE (s.status is null
List<Student> findAllByStatus(Status status);
列出findAllByStatus(状态);
但是,如果请求的状态为null,那么我希望检索状态为null的实体
如果状态为null,如何使用JPARepository仅使用一个方法查询来实现不按状态过滤
提前谢谢。试试看
@Query("SELECT s from Student s WHERE (s.status is null or s.status =?1)")
List<Student> findAllByStatus(Status status);
@Query(“从学生s中选择s,其中(s.status为null或s.status=?1)”)
列出findAllByStatus(状态);
此方法需要更多的代码,但我认为这是最好的选择:
@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);
}
@覆盖
公共列表findAllWithFilters(字符串名称、接口类型、字符串ip)
{
接口intfc=新接口();
intfc.setName(名称);
intfc.setType(类型);
intfc.setIp(ip);
ExampleMatcher matcher=ExampleMatcher.matching()
.withMatcher(“名称”,匹配->匹配.contains())
.withMatcher(“type”,match->match.exact())
.withMatcher(“ip”,匹配->匹配.contains())
.具有忽略路径(“id”、“uuid”)
.withIgnoreNullValues();
Example Example=Example.of(intfc,matcher);
return((InterfaceRepository)baseRepository).findAll(示例);
}
.withIgnoreNullValues()是键。如果发送空值而不是枚举常量,它将返回所有内容。JPA正在生成带等号的SQL语句。将null与等号进行比较在大多数DBMS中不起作用。相反,需要
is
关键字:
WHERE (s.status =?1 and ?1 is not null) or (s.status is null and ?1 is null)
您应该使用以下内容:
@Query("SELECT s from Student s WHERE (?1 is null or s.status = ?1)")
List<Student> findAllByStatus(Status status);
@Query(“从学生s中选择s,其中(?1为null或s.status=?1)”)
列出findAllByStatus(状态);
只需对Ankit Kanani Ankey进行一点修改。已经提供了一个findAll方法,如果状态为null,则改为调用该方法。