【发布时间】:2019-10-14 12:47:11
【问题描述】:
我有这些模型和存储库:
(跳过所有不相关的字段和 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 存储库为您提供的所有这些好处)。而且我也不知道该怎么做:-)
所以我想知道是否有一个简单的解决方案。
【问题讨论】:
-
你能显示 Contact 和 targetGroups 类吗
-
或许
@Query("SELECT c FROM Contact c WHERE c.targetGroups.id IS NOT NULL") -
我想你要找的是
JpaSpecificationExecutor。您可以将其添加到您的界面中,例如public interface ContactRepository extends CrudRepository<Contact, Integer>, JpaSpecificationExecutor<Contact>,但这就是我可以提供的全部内容,因为我以前没有使用过:查看更多示例:javadeveloperzone.com/spring/spring-jpa-dynamic-query-example -
那些是你要找的机器人吗? stackoverflow.com/questions/14340156/…
-
@Thomas 是的,这看起来与我正在寻找的完全一样。谢谢你一百万次!
标签: java jpa spring-data-jpa