【问题标题】:spring jpa handling null value in max queryspring jpa在最大查询中处理空值
【发布时间】:2014-11-03 19:02:26
【问题描述】:

我正在尝试使用此查询从数据库中选择一个序列 ID:

@Query("select max(pi.sequence) + 1 from ProductImage pi where pi.product = :product")
    int nextSequenceForProduct(@Param("product")Product product);

它运行良好,除非表中没有值,它会从 JPA 代码中抛出某种类型的空值异常。

有没有办法在 spring jpa 中处理 null 值?例如像这样的 SQL:

select ifnull(max(pi.sequence),1) from ....

【问题讨论】:

  • 您是否尝试过类似的方法:"select case when (pi.sequence is null) then 1 else (max(pi.sequence) + 1) end from ProductImage pi where pi.product = :product"

标签: spring jpa spring-data-jpa


【解决方案1】:

您可以使用 nvl() 函数并将查询更改为本地查询或命名本地查询以避免异常

@NativeQuery("select nvl(max(pi.sequence),0) + 1 from ProductImage pi where pi.product = :product")

【讨论】:

  • JPQL 中没有“NVL”
  • 那么最好将查询设为原生查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 2021-06-27
  • 2018-04-22
  • 1970-01-01
相关资源
最近更新 更多