我有這些模型和存儲庫:(跳過所有不相關(guān)的字段和 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方法返回具有所提供的目標(biāo)組 ID 之一的聯(lián)系人。這很好用。現(xiàn)在我需要選擇具有所有提供的目標(biāo)組 ID 的聯(lián)系人。用JPA可以嗎?我能想到的就是將查詢手動構(gòu)建為字符串,然后使用實(shí)體管理器執(zhí)行它,但這會帶來無數(shù)其他問題(分頁、排序、投影以及 JPA 存儲庫為您提供的所有這些好處)。而且我也不知道該怎么做:-)所以我想知道是否有一個簡單的解決方案。
1 回答

呼喚遠(yuǎn)方
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個贊
問題已經(jīng)有了解決方案 -使用 jpql 查找包含給定集合所有元素的集合的項(xiàng)目
我決定在這里分享我的問題的確切解決方案代碼,也許它會對某人有所幫助:
@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);
添加回答
舉報(bào)
0/150
提交
取消