JPQL如何获取所有被引用的实体而不仅仅是被搜索



假设我有两个实体——Item和Tag。每个项目都有一个标签列表。我想提供一个标签id列表,并返回包含这些标签的所有项目。当前查询类似于select item from Item item join fetch item.tags tags where tags.id in tagIds。只获取提供的标签(例如:如果我只提供一个标签id, item。tags包含一个标签),但我想获取所有标签。我正在使用spring数据,所以jpa提供程序是hibernate,我猜。

您必须使用左连接来获取所有。

按如下方式修改查询。

@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中选择不同的t.item

如果子实体在"where"条款。绕过它的一种方法是执行子查询:

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

最新更新