HQL查询以检查集合的大小是0还是空

时间:2010-09-21 13:25:34

标签: sql hibernate hql

我尝试生成一个HQL查询,其中包含一个空的appoinment集合的用户(由OneToMany映射):

SELECT u FROM User u JOIN u.appointments uas WHERE u.status = 1 AND (uas.time.end < :date OR size(uas) = 0)

我尝试了几种方式(NOT EXIST ELEMENT(), IS NULL) 另见:How to check if the collection is empty in NHibernate (HQL)?(这对我不起作用)

但仍然不是我想看的结果或HQL或SQL SERVER中的一些错误

注意:

没有JOIN的查询有效:

"FROM User u WHERE u.status = 1 AND size(u.appointments) = 0"

解决

另一个JOIN解决了这个问题:

SELECT u FROM User u LEFT JOIN u.appointments pas1 LEFT JOIN pas1.slot t WHERE u.status = 1 AND t.end <= :date1 OR t.end IS NULL ORDER BY u.name asc

4 个答案:

答案 0 :(得分:42)

使用IS EMPTY应该有效(我赞成使用JPQL语法):

SELECT u FROM User u WHERE u.status = 1 AND u.appointments IS EMPTY

如果没有,请显示生成的SQL。

参考

  • Hibernate核心参考指南
  • JPA 1.0规范
    • 第4.6.11节“空集合比较表达式”

答案 1 :(得分:13)

您是否看过生成的SQL?你的方法在这里工作正常:

// Hibernate query:
const string hql = "from User u where u.Id = 101 and size(u.Appointments) = 0";


// Generates this working SQL:
select user0_.Id    as Id20_,
       user0_.Name as Name2_20_
from   User user0_
where  user0_.Id = 101
       and (select count(appointment1_.Id_Solicitud)
            from   Appointment appointment1_
            where  user0_.Id = appointment1_.Id_User) = 0

答案 2 :(得分:6)

// Hibernate query:
const string hql = "from User u where u.Id = 101 and size(u.Appointments) = 0";

答案 3 :(得分:0)

以下查询将起作用。诀窍是使用 LEFT 连接。

SELECT u FROM User u LEFT JOIN u.appointments uas 
WHERE u.status = 1 AND 
(uas.time.end < :date OR size(u.appointments) = 0)