简体   繁体   English

Java JPA查询将忽略搜索字段为null的记录

[英]Java JPA query is ignoring records where a searched field is null

This JPA query 此JPA查询

    @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). 应该会按预期返回e.field1 IN:collectionOfField1s和e.status <>被“删除”的所有记录,但是不幸的是,它没有返回e.status仍然为null (尚未填充)的记录。 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. 我想知道我需要更改什么,以便它返回e.field1 IN:collectionOfField1s和e.status <>'已删除'的所有记录,包括e.status为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. 在数据库中,Null是非常具体的事情,您需要以不同的方式对待它。 You have at least two ways to achieve what you want. 您至少有两种方法可以实现所需的目标。 The first is specify that NULL is a expected value, as follow: 第一个是指定NULL是期望值,如下所示:

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: 另一种方法是使用称为COALESCE的特殊功能,如下所示:

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. 在这种情况下,如果找到空值,则应假定为“已删除”值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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