【问题标题】:How to prevent empty List Error in Hibernate?如何防止休眠中的空列表错误?
【发布时间】:2013-07-09 19:49:48
【问题描述】:

我在休眠中有以下 HQL 查询:

select x 
from Item as x
where x not in (select o.item from Opinion as o where o.user =:user)

除非子查询 (select o.item from Opinion as o where o.user =:user) 返回一个空列表,否则此查询工作正常。在这种情况下,我得到了一个错误。

当子查询 (select o.item from Opinion as o where o.user =:user) 为空时,有没有办法防止 Hibernate 引发错误?

我如何必须重写查询以使其即使对于空 (select o.item from Opinion as o where o.user =:user) 也能正常工作?

【问题讨论】:

  • 这是 SQL 还是 HQL?如果是 SQL,您使用的是哪个数据库?

标签: spring hibernate grails


【解决方案1】:

我看到的一个简单的方法是

select x 
from Item as x
where (select count(distinct o.item) from Opinion as o where o.user =:user) = 0

或(*未经测试)

select x 
from Item as x
where not exists (from Opinion as o where o.item = x and o.user =:user)

【讨论】:

  • 假设我需要 select x from Item as x where x in :someList 如果 someList 为空,我该怎么做才能不发生错误?
  • @confile 上述方法对您来说是否失败?
  • 第二个工作正常。但是当我想要 x in (...) 时我该怎么做
  • @confile 试试coalesce看看能不能得到你需要的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2013-03-25
相关资源
最近更新 更多