【问题标题】:Spring jpa @query is not working when date value is null当日期值为空时,Spring jpa @query 不起作用
【发布时间】:2020-08-28 20:17:40
【问题描述】:

我正在使用 JPA,并且我使用了 @Query 连接两个表,现在我的要求是我可以在 where 条件下组合可能的值,有些可能为 null 或空。

我的@Query 包含(value = "Select * From A a Left Outer Join B b On A.Id=B.Id where :fromDate is NULL and :toDate is NULL or B.Activity_Date_Time Between :fromDate AND :toDate")**

我在查询中处理这个问题,它对 String 工作正常,但对于 TIMESTAMP 却给出错误,因为

嵌套异常是 org.hibernate.exception.SQLGrammarException: could 不提取 ResultSet] 的根本原因 java.sql.SQLSyntaxErrorException:ORA-00932:不一致的数据类型: 预期的 TIMESTAMP 得到 BINARY

我在日志中从 JPA 生成 SQL,在 SQL 开发人员上运行良好

Select
        * 
    From
        table A 
    Left Outer Join
        table B 
            On A.Id=B.Id     
    Where (
            A.Customer = 'fsfsfsdfsfd'
        )    
        and (
            null is null 
            and null is null 
            or B.Activity_Date_Time Between null AND null
        ) 
        And (
            'MATURITY' is null 
            or B.Activity_Type = 'MATURITY'
        );

【问题讨论】:

  • 请向我们展示您正在使用的完整方法和生成的SQL。请将两者都格式化为源代码。

标签: hibernate jpa spring-data-jpa


【解决方案1】:

问题在于您的查询参数:fromDate 和:toDate,您从代码中传递了具有空值的参数。另请参阅您的查询:

Select
        * 
    From
        table A 
    Left Outer Join
        table B 
            On A.Id=B.Id     
    Where (
            A.Customer = 'fsfsfsdfsfd'
        )    
        and (
            null is null 
            and null is null 
            or B.Activity_Date_Time Between null AND null
        ) 
        And (
            'MATURITY' is null 
            or B.Activity_Type = 'MATURITY'
        );

你的命名参数被 null 替换,如果你用 null 检查 null,这将是一个二进制操作。因此尝试将时间戳从代码传递给 @Query 以摆脱这种情况。

【讨论】:

  • 只是另一个怀疑它适用于字符串参数,仅适用于其他数据类型失败。
  • 只是因为默认值 null 在您的其他数据类型的情况下被传递,以防万一请分享您的代码。
猜你喜欢
  • 2021-11-17
  • 2020-05-09
  • 2018-03-20
  • 2021-03-31
  • 2019-08-03
  • 2018-03-31
  • 2017-06-01
  • 2018-07-05
  • 2018-01-24
相关资源
最近更新 更多