JPA join fetch query with many to many

一个人想着一个人 提交于 2019-12-11 07:08:28

问题


I have an object Favourite. This object has a many to many connection with Colors. Lets say that some favourites have many colors, 2-3 etc. When I search for a favourite like:

SELECT fav FROM Favourite fav join fetch fav.colors as cl WHERE fav.name = "blabla" .

The resulting object contains all the colors related to this favourite. My problem is when I want to search for a favourite that has a certain color. For example:

SELECT fav FROM Favourite fav join fetch fav.colors as cl WHERE cl.name = "red" 

Then the resulting object contains only the red color. I want to get as a result the fav objects that contain the "red" color, but also show all the related colors. Any suggestions? Thanks in advance.


回答1:


Well finally it worked with an inner query and "EXISTS" operator. (color is an object of , int id and string name).

SELECT fav FROM Favourite fav join fetch fav.colors as cl WHERE EXISTS ( SELECT fav2 FROM Favourite fav2 join fetch fav2.colors as cl2 WHERE fav2.id = fav.id AND cl2.name = "red" )


来源:https://stackoverflow.com/questions/12051559/jpa-join-fetch-query-with-many-to-many

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