我有這些模型和存儲庫:(跳過所有不相關的字段和 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
提交
取消