假设我有 2 个实体 - 项目和标签。每个项目都有一个标签列表。我想提供标签 ID 列表并返回包含这些标签的所有项目。 当前查询就像
select item from Item item join fetch item.tags tags where tags.id in tagIds
。
只获取提供的标签(例如,如果我只提供一个标签 ID,则 item.tags 包含该标签),但我想获取所有标签。
我正在使用 spring 数据,所以我猜 jpa 提供程序是休眠的。
你必须使用左连接来获取所有。
如下更改您的查询。
@Query("select item from Item item left join fetch item.tags tags where tags.id in :tagIds")
List<Item> findItemsByTagIds(@Param("tagIds") List<Long> listOfTagIds);
如果你想要不同的项目,那么你可以在选择后使用不同的关键字。
如果你有从标签到项目的反向关系,你可以请求:
select distinct t.item from Tag t where t.id in tagIds
JPA 似乎过滤了位于“where”子句中的子实体。一种解决方法是进行子查询:
select item from Item item left join fetch item.tags tags where exists(select t from tags where t.id in :tagsIds)