Search code examples
springhibernatejpajpql

JPQL how to fetch all referenced entities and not just searched by


Let's say I have 2 entities - Item and Tag. Every Item has a list of Tags. I want to supply a list of tag ids and return all items that contain those tags. Currently query is like select item from Item item join fetch item.tags tags where tags.id in tagIds. Only supplied tags are getting fetched(E.g. if I supply just one tag id, item.tags contains that one tag), but I'd like to fetch all of them. I'm using spring data, so jpa provider is hibernate, I guess.


Solution

  • It seems that JPA filters child entities if they are in "where" clause. One way around it is making a subquery:

    select item from Item item left join fetch item.tags tags where exists(select t from tags where t.id in :tagsIds)