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

Mic*_*hel 25 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)
Run Code Online (Sandbox Code Playgroud)

我尝试了几种方式(NOT EXIST ELEMENT(), IS NULL)也看到:如何在NHibernate(HQL)中检查集合是否为空?(这对我不起作用)

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

注意:

没有JOIN的查询有效:

"FROM User u WHERE u.status = 1 AND size(u.appointments) = 0"
Run Code Online (Sandbox Code Playgroud)

解决了

另一个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
Run Code Online (Sandbox Code Playgroud)

Pas*_*ent 45

使用IS EMPTY应该工作(我赞成JPQL语法):

SELECT u FROM User u WHERE u.status = 1 AND u.appointments IS EMPTY
Run Code Online (Sandbox Code Playgroud)

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

参考

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


reb*_*ard 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
Run Code Online (Sandbox Code Playgroud)


小智 6

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

  • 一点点解释会让你的答案变得更好.:) (3认同)
  • 其中size()= 0适用于我,其中IS Empty不受支持.谢谢! (2认同)