使用转换为NULL的Converter生成正确的SQL?

时间:2014-05-05 15:44:05

标签: java sql oracle jpa jpql

我有一个命名查询:

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

问题是状态是Boolean参数,通过AttributeConverter转换为&#34; +&#34;如果状态为trueNULL,则状态为false

我通过javax.persistence.Converter.AttributeConverter<Boolean, String>

执行此操作

如果状态为true,则效果正常但如果为false则会出错:

  

内部异常:java.sql.SQLSyntaxErrorException:ORA-01722:无效的数字

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

  

(t0.STATUS =?)

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

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

1 个答案:

答案 0 :(得分:1)

您可以尝试使用NVL:

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

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

  1. 您必须确保'not_real_value'无法发生
  2. 您几乎选择不使用状态列
  3. 上的索引(除非您使用函数索引)

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

    where ((:status is not null and status = :status) or (status is null and :status is null))
    
相关问题