微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我们如何使用 Criteria Query 在 Spring JPA 中查询一对多关系

如何解决我们如何使用 Criteria Query 在 Spring JPA 中查询一对多关系

场景是: 实体学生 ID 名称 列出课程

实体课程 ID 名称 学生

现在我需要正在学习“编程”课程的学生名单

如何使用 Criteria Query 实现这一点。

解决方法

试试这个:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);

Root<Student> rootStudent = cq.from(Student.class);
Join<Student,Course> joinCourse = rootStudent.join("courses",JoinType.INNER);

cq.where(cb.equals(joinCourse.get("Name"),"Proggraming"));
cq.select(rootStudent);

List<Student> res = entityManager.createQuery(cq).getResultList();

在此示例中,我假设您对 JPA 实体进行了良好建模,包括双向关系。如果 API 使用 pojos 而不是将 JPA 实体返回到 Web 部件,也建议您使用多选而不是选择并指定要获取的每个字段,但作为第一个近似值是有效的。

建议对 JPA 实体使用元模型,而不是通过带有名称的字符串访问属性(join、get methods ..)

在这种情况下,创建子查询没有意义,我更改查询以通过子查询查找课程 Proggraming1 或 Proggraming2 的学生(我仍然更喜欢通过过滤连接而不使用子查询来做到这一点) ,它会是这样的:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);

Root<Student> rootStudent = cq.from(Student.class);
Join<Student,JoinType.INNER);

Subquery<Long> subqueryIdCourse = cq.subquery(Long.class);
Root<Course> rootCourseSq = subqueryIdCourse.from(Course.class);
subqueryIdCourse.where(
    cb.or(
        cb.equals(rootCourseSq.get("Name"),"Proggraming1"),cb.equals(rootCourseSq.get("Name"),"Proggraming2")))
subqueryIdCourse.select(rootCourseSq.get("ID"))

cq.where(joinCourse.get("ID").in(subqueryIdCourse.getSelection()));
cq.select(rootStudent);

List<Student> res = entityManager.createQuery(cq).getResultList();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。