Reputation: 5246
I have 3 tables named School, SchoolType and Country. You can see the relationship between School and SchoolType. What I want to query is;
Select countries which has same id with Schooltypes that has at least one school named "blabla".
My School class;
@JoinColumn(name = "school_type_ref", referencedColumnName = "school")
@ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
private SchoolType schooltype;
My SchoolType Class;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "schooltype")
private List<School> schoolList;
private String id;
My Country Class;
private String id;
Upvotes: 2
Views: 10523
Reputation: 913
Check this:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Country> c = cb.createQuery(Country.class);
Root<Country> countries = c.from(Country.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<SchoolType> schoolTypes = sq.from(SchoolType.class);
sq.select(schoolTypes.<Integer>get("id")).where(
cb.equal(schoolTypes.get("schoolList").get("name"), "blabla"));
c.select(countries).where(cb.in(countries.<Integer>get("id")).value(sq));
TypedQuery<Country> q = entityManager.createQuery(c);
List<Country> result = q.getResultList();
Also instead of schoolTypes.<Integer>get("id")
you can try use schoolTypes.get(SchoolType_.id)
but it never works for me.
My answer is basing on JPA 2.0, Criteria API, Subqueries, In Expressions
Upvotes: 1