[英]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.