首页 文章

HQL / SQL / Criteria加入 - 匹配给定列表中的所有记录,同时选择所有字段

提问于
浏览
2

我正在尝试编写一个HQL / Criteria / Native SQL查询,它将返回分配给Projects列表的所有Employees . 必须将它们分配给所有项目才能被选中 .

使用本机SQL实现此目的的可接受方法可以在这个问题的答案中找到:T-SQL - How to write query to get records that match ALL records in a many to many join

SELECT e.id 
FROM employee e 
    INNER JOIN proj_assignment a 
        ON e.id = a.emp_id and a.proj_id IN ([list of project ids])
GROUP BY e.id
HAVING COUNT(*) = [size of list of project ids]

但是,我想选择Employee的所有字段( e.* ) . 不可能定义SQL grouping by all the columnsGROUP BY e.* ),而应该使用 DISTINCT . 有没有办法使用 DISTINCTCOUNT(*) 一起实现我想要的?

我也尝试使用HQL来执行此查询 . EmployeeProjectAssignment 类不能使用Criteria加入它们 . 我使用交叉连接,因为它是执行Join without association in HQL的方式 . 所以,我的HQL看起来像

select emp from Employee emp, ProjectAssignment pa 
where emp.id = pa.empId and pa.paId IN :list 
group by emp having count(*) = :listSize

但是,由于Hibernate中的一个错误,GROUP BY entity does not work . 它输出的SQL类似于 group by (emptable.id) .

为每个项目分配分配表(为列表中的每个项目动态添加 and exists (select 1 from proj_assignment pa where pa.emp_id=e.id and pa.proj_id = [anId]) )是不可接受的选项 .

有没有办法正确地编写这个查询,最好是在HQL中(最后我想要 List<Employee> ),而不修改映射并且没有显式选择本机SQL中的所有列?


EDIT :我正在使用Oracle 10g和hibernate-annotations-3.3.1.GA

2 回答

  • 0

    怎么样:

    select * from employee x where x.id in(
    SELECT e.id 
    FROM employee e 
        INNER JOIN proj_assignment a 
            ON e.id = a.emp_id and a.proj_id IN ([list of project ids])
    GROUP BY e.id
    HAVING COUNT(*) = [size of list of project ids]
    )
    
  • 0

    我已经找到了另一种在HQL中实现这一点的方法,它比我想要的效率要低得多(而且没有那个令人讨厌的bug,真的可能),但至少它有效 . 它比重复每个项目的子选择更好

    and exists (select 1 from project_assignment pa where pa.id = someId and pa.emp_id = e.id)
    

    它包括执行自连接子查询,以便为每个Employees找出它们分配给列表中的项目数量,并将结果限制为仅包含在所有项目中的项目 .

    select e 
    from Employee
    where :listSize = 
        (select distinct count(*)
         from Employee e2, ProjectAssignment pa
         where 
             e2.id = pa.id_emp and 
             e.id = e2.id
             and pa.proj_id IN :projectIdList
        )
    

相关问题