gpt4 book ai didi

java - 使用转换为 NULL 的转换器生成正确的 SQL?

转载 作者:行者123 更新时间:2023-12-01 13:01:36 25 4
gpt4 key购买 nike

我有一个命名查询:

<query>
select data
from objects obj
where obj.status = :status
</query>

问题是状态是 Boolean通过 AttributeConverter 转换的参数如果状态为true,则为“+”或NULL如果状态是false

我通过javax.persistence.Converter.AttributeConverter<Boolean, String>来做到这一点

如果状态为true,则效果很好。但如果是false我收到错误:

Internal Exception: java.sql.SQLSyntaxErrorException: ORA-01722: invalid number

我可以在错误日志中看到生成的 SQL 查询包含以下表达式:

(t0.STATUS = ?)

这是不正确的,因为它实际上应该是:`(t0.STATUS IS NULL)

如果值转换为NULL,我期望 JPQL 自动生成预期的查询。 。有没有办法实现这一点,或者转换器不适合以这种方式使用?

最佳答案

您可以尝试使用NVL:

where nvl(status, 'not_real_value') = nvl(:status, 'not_real_value')

这个常见的解决方案几乎没有问题:

  1. 您必须确保“not_real_value”不会发生
  2. 您几乎选择不在状态列上使用索引(除非您使用函数索引)

所以这是另一个没有任何妥协的解决方案:

where ((:status is not null and status = :status) 
or (status is null and :status is null))

关于java - 使用转换为 NULL 的转换器生成正确的 SQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23476547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com