我有这些模型和存储库:(跳过所有不相关的字段和 getter/setter)public class Contact { @Id private Integer id; private String name; @ManyToMany private List<TargetGroup> targetGroups = new ArrayList<>();}public class TargetGroup { @Id private Integer id; @NotBlank private String name;}@Repositorypublic interface ContactRepository extends CrudRepository<Contact, Integer> { @Query("SELECT c FROM Contact c JOIN c.targetGroups tg " + "WHERE (tg.id IN :targetGroups)") Page<ContactView> customFilterWithTargetGroups(@Param("targetGroups") Set<Integer> targetGroups, Pageable pageable);}简而言之,customFilterWithTargetGroups方法返回具有所提供的目标组 ID 之一的联系人。这很好用。现在我需要选择具有所有提供的目标组 ID 的联系人。用JPA可以吗?我能想到的就是将查询手动构建为字符串,然后使用实体管理器执行它,但这会带来无数其他问题(分页、排序、投影以及 JPA 存储库为您提供的所有这些好处)。而且我也不知道该怎么做:-)所以我想知道是否有一个简单的解决方案。
1 回答

呼唤远方
TA贡献1856条经验 获得超11个赞
问题已经有了解决方案 -使用 jpql 查找包含给定集合所有元素的集合的项目
我决定在这里分享我的问题的确切解决方案代码,也许它会对某人有所帮助:
@Query("SELECT c FROM Contact c JOIN c.targetGroups tg " +
"WHERE (tg.id IN :targetGroups)" +
" GROUP BY c.id HAVING count(c.id) = :groupsCount")
Page<ContactView> customFilterWithTargetGroups (@Param("targetGroups") Set<Integer> targetGroups, @Param("groupsCount") long groupsCount, Pageable pageable);
添加回答
举报
0/150
提交
取消