Selecting where an entity contains a list thats a subset of another list

对着背影说爱祢 提交于 2019-12-17 16:11:02

问题


I am writing a JPQL query and i have the following scenario. I have a Question entity which contains a list of Tags. I would like to select all Questions that contains a given List of tags. How do i do this with JPA?

I would like to do something like SELECT x FROM Question x WHERE x.tags 'contains all' :tags


回答1:


[This searches for ANY not ALL; please refer other correct answers.]

You can set list as a parameter.

SELECT x FROM Question x WHERE x.tags IN :tags

Also try using (:tags), as it depends on the JPA implementation you are using.




回答2:


Try like this:

select distinct q from Question q join q.tags as t 
where t.name in (:tags) 
group by q.id, q.author, q.title, q.content,q.postedAt 
having count(t.id) = :size



回答3:


Nayans solution does'nt work for me. Its selecting every 'x' which matches the first (or any?) entry of the given collection ':tags'. If this really worked for you, you should test you application again ;) might be JPA dependend - I don't know.

Tip: Try Krzysztofs solution or use mine:

SELECT x FROM Question x 
WHERE x IN (
    SELECT y FROM Question y
    INNER JOIN y.tags yt
    WHERE yt IN (
        :tags
    )
    GROUP BY y
    HAVING COUNT( DISTINCT yt) = (
        :tagsSize // should be clear ;)
    )
)


来源:https://stackoverflow.com/questions/4638543/selecting-where-an-entity-contains-a-list-thats-a-subset-of-another-list

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