我有以下模型和存储库:
(跳过所有不相关的字段和获取/设置者)
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;
}
@Repository
public 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存储库为您提供的所有便利)。而且我也不知道怎么做:-)
所以我想知道是否可能有一个简单的解决方案。
最后,正如@Thomas所指出的,这里已经存在解决我的问题的方法- 使用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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句