为啥当参数为null时,postgres会抛出异常?

Posted

技术标签:

【中文标题】为啥当参数为null时,postgres会抛出异常?【英文标题】:Why when parameter is null, postgres throws an exception?为什么当参数为null时,postgres会抛出异常? 【发布时间】:2022-01-15 11:31:35 【问题描述】:
@Query(value = "select distinct m from MerchantStore m 
left join fetch m.parent mp left join fetch m.country mc 
left join fetch m.currency mc left join fetch m.zone mz 
left join fetch m.defaultLanguage md 
left join fetch m.languages mls where (?1 is null or m.storename like %?1%)",
countQuery = "select count(distinct m) from MerchantStore m where (?1 is null or m.storename like %?1%)")
    
Page<MerchantStore> listAll(String storeName, Pageable pageable);

我有上面的查询,但它抛出了以下异常:

PSQLException: ERROR: operator does not exist: character varying ~~ bytea
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

当我将条件旋转到(m.storename like %?1% or ?1 is null) 时,它可以正常工作。

有人可以向我解释一下这里到底发生了什么吗? 附言这是来自 Shopizer 库 PageableMerchantRepository.java。

【问题讨论】:

?1 is null 是什么意思?就像storeName = "StarBucks" 你将拥有"starbucks" is null 实际发送到数据库的查询是什么? 您在哪个查询中轮换条件?那不应该是m.storename is null吗? @AlbertoSinigaglia 这是不想动态组合查询的程序员常用的(如果不幸的话)捷径。 “如果我提供 NULL 参数,则此表达式始终为真”是一种忽略表达式的另一个分支的方法,而无需将其从查询中删除。 @jjanes 那么我该如何解决呢?正确的方法是什么?这不是我的代码,我之前没有使用过 Query。他们写的每一个查询都是这样,当我设置数据库时,它们都不起作用。 【参考方案1】:

这可能是因为MerchantStore.storename 是一个不可为空的字段/列! ;)

(?1 is null or m.storename like %?1%)

显然 postgres 似乎不喜欢哪个(用我的话来说:“null 不是该列的有效'数据类型'”),而在:

(m.storename like %?1% or ?1 is null)

?1 is null(显然!?)从未评估过。

那就这样吧:

m.storename like %?1%

,并确保不传递空值/如何处理它们(like %null%like '%'?)。

【讨论】:

以上是关于为啥当参数为null时,postgres会抛出异常?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Double.parseDouble(null) 和 Integer.parseInt(null) 会抛出不同的异常?

为啥非空列表会抛出空指针异常?

为啥从 BigDecimal 转换为 DECIMAL 时 impala-jdbc 会抛出异常?

为啥 String.valueOf(null) 会抛出 NullPointerException?

为啥Visual Studio在声明字符串数组列表时会抛出异常

当它应该表现得像 try/catch/finally 时,为啥使用会抛出异常?