Raymond Stanley Raymond Stanley - 5 months ago 14
Java Question

JPA IN clause for one to many relationship

I have the following jpa entities:

Music_playlist[

Integer music_id;

Integer playlist_id;

List<Genre> genres;
]

Genre[
Integer genre_id;
]


I want to know if I can make a named query that is going to retrieve music_playlist entities which their genres attributes contains a genre object with a genre_id equals to a named param. Something like this:

SELECT mp FROM music_playlist WHERE :genreId in mp.genres.genre_id

Answer

You can use ANY

 FROM MusicPlaylist mp WHERE 'Rock' = ANY (SELECT g.genreId FROM mp.genres g)