简体   繁体   English

JPA CriteriaQuery OneToMany

[英]JPA CriteriaQuery OneToMany

I have two entities with a OneToMany relationship. 我有两个具有OneToMany关系的实体。 To make it simple, let's suppose them as School and Students, with a unidirectional relationship from school to students. 为了简单起见,让我们假设他们是学校和学生,从学校到学生的单向关系。 I want to find the school object that has a specific student (a student with a specific age, name, ssn, ...). 我想找到一个具有特定学生的学校对象(具有特定年龄,姓名,ssn的学生......)。 I know that I can create a simple criteria as the following for simple School's properties (for School's name, as the following): 我知道我可以为简单的学校属性创建一个简单的标准(对于学校的名称,如下所示):

ParameterExpression<String> p = criteriaBuilder.parameter(String.class, "schoolName");
            criteria = criteriaBuilder.and(criteria, criteriaBuilder.like(schoolRoot.get("schoolName") , p));
queryResult.setParameter("schoolName", schoolName + "%");

but, how can I query students with a specific property value while the students is represented as a java.util.List instead of being a basic property? 但是,如果学生被表示为java.util.List而不是基本属性,我如何查询具有特定属性值的学生?

Can somebody can help me figure this out? 有人可以帮我解决这个问题吗? I hope I have been able to explain my problem. 我希望我能够解释我的问题。

Thanks 谢谢

CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<School> query = criteriaBuilder.createQuery(School.class);
Root<School> schoolRoot = query.from(School.class);
Join<School, Student> join = schoolRoot.join(School_.students);
query.where(criteriaBuilder.equal(join.get(Student_.name), "john"));

It looks up a student with name john in all schools. 它在所有学校中查找名为john的学生。

我想这会做类似的事情;

FROM School sch WHERE 'Student Name' = ANY (SELECT stud.name FROM sch.students stud)

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

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