我有这些模型和存储库:
(跳过所有不相关的字段和 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;
}
@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 存储库为您提供的所有这些好处)。而且我也不知道该怎么做:-)
所以我想知道是否有一个简单的解决方案。
呼唤远方
相关分类