Seleccionar dónde una entidad contiene una lista que es un subconjunto de otra lista

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

preguntado el 09 de enero de 11 a las 09:01

3 Respuestas

[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.

respondido 21 nov., 17:10

I will test this in a short while. I know it works if am checking if one tag is in a list of tags. But now my situation involves testing if a list of tags is a subset of another list of tags. - Joshua

Does not work. It returnes a 'Question' where ':tags' contain any element in 'x.tags'. - XiCoN JFS

This doesn't work, didn't even pass sql prepare check. - AttitudeL

Intente así:

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

Respondido 26 Feb 12, 19:02

This answer worked for me using MySQL. @nayan-wadekar answer was giving sql grammar exceptions. - malloc4k

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.

Sugerencia: prueba 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 ;)
    )
)

contestado el 23 de mayo de 17 a las 15:05

Can't the tagsize check be fooled by you requiring two tags. and the question having two but only matching one? - Amalgovinus

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.