【问题标题】:CriteriaBuilder: join one-to-many with ON clauseCriteriaBuilder:使用 ON 子句加入一对多
【发布时间】:2018-03-29 08:34:57
【问题描述】:

假设您有以下 OneToMany 关系:School->Student->ScientificWork。现在,您要选择所有拥有名为“约翰”的学生且他的科学工作称为“黑洞”的学校。

我按照以下方式进行操作,但由于某种原因,它会返回所有可能的学校。

public static Specification<School> spec() {
    return (root, query, cb) -> {
        final SetJoin<School, Student> studs = root.joinSet("students", JoinType.LEFT);
        final SetJoin<Student, ScientificWork> works = root.joinSet("works", JoinType.LEFT);
        return cb.and(
                cb.equal(studs.get(Student_.name), 'John'),
                cb.equal(nodes.get(ScientificWork_.name), 'Black Holes')
        );
    };
}

更新

在找到this answer 之后,我尝试了以下方法,但结果相同(它返回给我的是所有学校而不是一个):

public static Specification<School> spec() {
    return (root, query, cb) -> {
        final SetJoin<School, Student> studs = root.joinSet("students", JoinType.LEFT);
        studs.on(cb.equal(studs.get(Student_.name), 'John'));
        final SetJoin<Student, ScientificWork> works = root.joinSet("works", JoinType.LEFT);          
        return cb.equal(nodes.get(ScientificWork_.name), 'Black Holes');
    };
}

【问题讨论】:

  • 这可能吗?有人需要其他详细信息吗?
  • 你是否误用了节点而不是作品?
  • 这一行 ` final SetJoin works = root.joinSet("works", JoinType.LEFT);` 应该是 ` final SetJoin works = studs.joinSet("works", JoinType.LEFT);` 还是打错了?

标签: hibernate spring-data-jpa spring-data criteria-api


【解决方案1】:
public static Specification<School> spec() {
return (root, query, cb) -> {
    final Join<School, Student> studs = root.join("students", JoinType.LEFT);
    studs.on(cb.equal(studs.get(Student_.name), "John"));
    final Join<Student, ScientificWork> works = studs.join("works", JoinType.LEFT);          
    return cb.equal(works.get(ScientificWork_.name), "Black Holes");
};

}

我使用 join 而不是 joinSet 并使用 **works**.get(ScientificWork_.name) 而不是 **nodes**.get(ScientificWork_.name)

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多