代码之家  ›  专栏  ›  技术社区  ›  Michel

用于检查集合大小是否为0或空的HQL查询

  •  24
  • Michel  · 技术社区  · 14 年前

    我尝试生成一个hql查询,其中包含具有空appointment集合(由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中的某些错误

    注:

    不带联接的查询工作:

    "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
    
    3 回复  |  直到 14 年前
        1
  •  41
  •   Pascal Thivent    14 年前

    使用 IS EMPTY 应该有效(我更喜欢JPQL语法):

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

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

    工具书类

    • 休眠核心参考指南
    • JPA 1.0规范
      • 第4.6.11节“空集合比较表达式”
        2
  •  13
  •   rebelliard    14 年前

    您是否查看了生成的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
    
        3
  •  5
  •   Youcef LAIDANI    7 年前
    // Hibernate query:
    const string hql = "from User u where u.Id = 101 and size(u.Appointments) = 0";