8

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 + "%");

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.

Thanks

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Azad
  • 399
  • 2
  • 6
  • 15

2 Answers2

6
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.

Vlasec
  • 5,500
  • 3
  • 27
  • 30
Azad
  • 399
  • 2
  • 6
  • 15
  • 2
    New to jpa here. How did you get the `School_.students`. I am trying a similar thing but dont know what this `_` means. – Vijay Kalidindi Sep 15 '17 at 10:04
  • @VijayKalidindi metamodel generation in JPA, Have a look at this. https://docs.jboss.org/hibernate/orm/5.0/topical/html/metamodelgen/MetamodelGenerator.html – BalaajiChander Feb 07 '18 at 09:35
0

I guess that would do the similar thing;

FROM School sch WHERE 'Student Name' = ANY (SELECT stud.name FROM sch.students stud)
erolkaya84
  • 1,769
  • 21
  • 28