HQL (Hibernate) how to check if a list of elements

2019-05-11 09:12发布

问题:

I am having tough time creating a HQL query that checks if a list of records 'a' of table 'X' is included within another list 'b' of the same table 'X'.

Here is an example i am using:

select r 
from Role r 
where (
    select p 
    from Permission p 
    where p.name = 'test') in elements(r.permissions)

Now this query is just as an example, to clarify a bit, each role has 1 or more permission.

Now here's what happen, if the the subselect (permission p) returns 1 row, all work fine. But if more are selected, the query fails, since I am trying to check if a list is within a list...

I am sure I am missing something here, so please any help would be appretiated.

Thanks

回答1:

Maybe something simpler exists, but I've not found it:

select r from Role r where not exists (
    select p.id from Permission p 
    where p.name = 'test'
    and p.id not in (select p2.id from Role r2 inner join r2.permissions p2
                     where r2 = r))

To make it clearer, this query checks that there is no permission of name 'test' that is not in the role permissions, which is the same as saying that all permissions with name 'test' are in the role permissions.