且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查 Spring 数据 JPA 查询中的 List 参数是否为空

更新时间:2023-11-29 17:01:58

好吧,我半夜醒来后想到一件事:

OK I though of a thing after waking up at the middle of the night :

@Query("SELECT DISTINCT c FROM Course c
" +
       "WHERE c.courseDate < CURRENT_TIME
" +
       "AND (?1 IS NULL OR (c.id NOT IN (3, 4, 5)))
" +
       "AND (?2 IS NULL OR (c.title LIKE ?2 OR c.description LIKE ?2))
" +
       "AND (COALESCE(?3) IS NULL OR (c.category IN ?3)) ")
List<Course> getCoursesFiltered(Long courseId, String filter, List<Category> categories);

解决方案只是在 IS NULL 之外使用 COALESCE,这样它就可以处理多个值.这样,如果列表包含至少一个非空值,则第二个表达式 ((c.category IN ?3)) 将完成过滤工作.

The solution was simply to use COALESCE in addition to IS NULL so it can work with multiple values. That way if the list contain at least one non-null value, the second expression ((c.category IN ?3)) will do the job of filtering.

下次我会至少等一整晚才问问题:)

I will wait at least a whole night next time before asking a question :)