简体   繁体   中英

Java JPA query is ignoring records where a searched field is null

This JPA query

    @Query("SELECT e FROM MyEntity e WHERE (e.field1 IN :collectionOfField1s AND TRIM(LOWER(e.status)) <> 'deleted')")

is supposed to return all records where e.field1 IN :collectionOfField1s and e.status <> 'deleted' as expected, but unfortunately it is not returning records where e.status is still null (not populated yet). I am wondering what do I need to change so that it returns all records where e.field1 IN :collectionOfField1s and e.status <> 'deleted', including those where e.status is null.

I appreciate any help on this.

Thank you

Null is a really specific thing in databases, and you need to treat it in a differente way. You have at least two ways to achieve what you want. The first is specify that NULL is a expected value, as follow:

SELECT e 
  FROM MyEntity e 
 WHERE e.field1 IN :collectionOfField1s 
   AND (e.status IS NULL OR TRIM(LOWER(e.status)) <> 'deleted')

The other way is use a special function called COALESCE, as below:

SELECT e 
  FROM MyEntity e 
 WHERE e.field1 IN :collectionOfField1s 
   AND (TRIM(LOWER(COALESCE(e.status, 'deleted'))) <> 'deleted')

In this case, if a null value is found, 'deleted' value should be assumed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM