JPA Query : How to check IS NULL or IS NOT NULL?

Viewed 680

I have below parameter which is

Boolean isActive = true/false

I need to pass this parameter in JPA Query.

true =  IS NOT NULL
false = IS NULL

@Query("select t from Test t WHERE t.active = ?1")
Optional<Test> findByIds(Boolean isActive);

How can I achieve this, rather than creating 2 separate queries for IS NULL & IS NOT NULL.

1 Answers

You can achieve that with the following way

@Query("select t from Test t WHERE (?1 = true AND t.active IS NOT NULL) OR
                                   (?1 = false AND t.active IS NULL")
Optional<Test> findByIds(Boolean isActive);
Related