JPA CriteriaQuery OneToMany [英] JPA CriteriaQuery OneToMany
问题描述
我有两个具有OneToMany关系的实体。为了简单起见,让我们假设他们是学校和学生,从学校到学生的单向关系。我想找到具有特定学生(具有特定年龄,姓名,ssn,......的学生)的学校对象。
我知道我可以为简单的学校属性创建一个简单的标准(对于学校的名称,如下所示):
I have two entities with a OneToMany relationship. 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, ...). 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 + "%");
但是,如果学生被表示为<$,我如何查询具有特定属性值的学生c $ c> java.util.List 而不是基本属性?
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?
有人可以帮我解决这个问题吗?我希望我能够解释我的问题。
Can somebody can help me figure this out? I hope I have been able to explain my problem.
谢谢
推荐答案
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"));
在所有学校中查找名为john的学生。
It looks up a student with name john in all schools.
这篇关于JPA CriteriaQuery OneToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!