【问题标题】:Criteria API in clause (filtering)子句中的 Criteria API(过滤)
【发布时间】:2019-03-11 14:38:15
【问题描述】:

嘿,我的查询有一个小问题。

我需要找到具有特定能力(如许可证和其他东西)的用户。

假设我有有能力的用户:

  • 亚历克斯:A、B、C
  • 约翰:A,B
  • 史蒂夫:B,C

请求:

  • workers?competences=A,B,C - 应该只返回 Alex
    • 目前返回 Alex 3 次,John 和 Steve 两次返回
  • workers?competences=A,C - 应该只返回 Alex
    • 目前返回 Alex 两次,John 和 Steve 一次
  • workers?competences=B,C - 应该返回 Alex 和 Steve
    • 目前返回 Alex 两次,Steve 两次,John 一次
  • workers?competences=B - 应该返回所有用户
    • 目前每个人都返回一次

目前它会找到所有具有能力 A 或 B 或 C 的用户。

我需要它来返回具有所有插入权限的用户所以competence A AND competence B AND competence C

这是我目前的规范:

public static Specification<WorkDetail> hasCompetences(String searchTerm) {
        return (root, query, criteriaBuilder) -> {
            List<String> list = new ArrayList<>(Arrays.asList(searchTerm.split(",")));
            Join join = root.join("competences");
            return join.get("name").in(list);
        };
    }

【问题讨论】:

    标签: java spring-boot criteria-api


    【解决方案1】:

    因为 Alex 有 3 个结果。我认为您的表结构如下所示

    name | competence
    -----------------
    Alex | A
    Alex | B
    Alex | C
    John | A
    John | B
    

    您当前在 sql 中的查询可能看起来像

    select name from competences where competence in ('A', 'B', 'C')
    

    您可能想添加distinct

    select distinct name from competences where competence in ('A', 'B', 'C')
    

    criteria API 中似乎是.distinct(true)

    更新

    IN 是一个OR 条件。如果您希望 name 仅具有所有权限,您应该执行以下操作(假设权限不会为一个人提供多个条目)

    select name from competences where competence in ('A', 'B', 'C') group by name having count(name) = 3;
    

    3IN数组的长度

    【讨论】:

    • 所以现在它不会返回重复的用户,这是向前迈出的一步,但是当它应该只返回 Alex 时,它仍然给了我所有具有 ?competences=A,B,C 的用户。它返回所有具有 A、B 或 C 的用户。我需要它是 A、B 和 C:/
    • 原来我毕竟需要 OR 变体,但更新似乎合乎逻辑!
    猜你喜欢
    • 2018-07-04
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多