【问题标题】:Select rows having ALL of the IN list references [duplicate]选择具有所有 IN 列表引用的行 [重复]
【发布时间】: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&lt;Contact, Integer&gt;, JpaSpecificationExecutor&lt;Contact&gt;,但这就是我可以提供的全部内容,因为我以前没有使用过:查看更多示例:javadeveloperzone.com/spring/spring-jpa-dynamic-query-example
  • 那些是你要找的机器人吗? stackoverflow.com/questions/14340156/…
  • @Thomas 是的,这看起来与我正在寻找的完全一样。谢谢你一百万次!

标签: java jpa spring-data-jpa


【解决方案1】:

最后,正如 @Thomas 所指出的,我的问题在这里已经有了解决方案 - Finding items with a set containing all elements of a given set with 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 2017-02-10
    • 2016-08-07
    • 2015-11-17
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多