简体   繁体   English

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

[英]How we query one to many relation in Spring JPA using Criteria Query

The scenario is: Entity Student ID Name List Courses场景为:实体学号名单课程

Entity Course ID Name Student实体 课程 ID 名称 学生

Now I need the list of students who are studying course 'Programming'现在我需要正在学习“编程”课程的学生名单

How can I achieve this using Criteria Query.如何使用 Criteria Query 来实现这一点。

try this:尝试这个:

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();

In this example I assume that you have the JPA entities well modeled, including bidirectional relationships.在此示例中,我假设您对 JPA 实体进行了良好建模,包括双向关系。 It would also be recommended if it is for an API that you use pojos instead of returning a JPA entity to the web part, for this you should use multiselect instead of select and specify each of the fields you want to obtain, but as a first approximation it would be valid. It would also be recommended if it is for an API that you use pojos instead of returning a JPA entity to the web part, for this you should use multiselect instead of select and specify each of the fields you want to obtain, but as a first近似值是有效的。

It would also be advisable to use metamodels for JPA entities instead of accessing the properties through a string with the name (join, get methods..)还建议对 JPA 实体使用元模型,而不是通过带有名称的字符串访问属性(连接、获取方法..)

In this scenario, it does not make sense to make a subquery, I change the query to find the students of the courses Proggraming1 or Proggraming2 through a subquery(I would still prefer to do it by filtering the joins without using subquery), it would be something like this:在这种情况下,进行子查询没有意义,我更改查询以通过子查询查找课程 Proggraming1 或 Proggraming2 的学生(我仍然希望通过过滤联接而不使用子查询来做到这一点),它会是这样的:

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);

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM