HQL (Hibernate) how to check if a list of elements is a subset of another list?

橙三吉。 提交于 2019-12-22 08:22:34

问题


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.



来源:https://stackoverflow.com/questions/11469575/hql-hibernate-how-to-check-if-a-list-of-elements-is-a-subset-of-another-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!