Reputation: 971
I am trying to solve the following problem with JPA specifications:
Consider the following classes:
public class Language {
private String name;
...
}
public class Person {
private List<Language> languages;
...
}
How do I select all Person
s, that speak a language with name x
? I am looking for a solution using the CriteriaBuilder
, which should generate a Predicate
that I can 'and' together with other predicates.
Thanks in advance.
Upvotes: 0
Views: 3996
Reputation: 3228
It is actually pretty easy:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> query = cb.createQuery(Person.class);
Root<Person> root = query.from(Person.class);
ListJoin<Person, Language> langJoin = root.join(Person_.langs);
query.where(cb.equal(langJoin.get(Language_.name), lang));
So you basically join the languages via corresponding association and then add an equals
predicate matching the required attribute of the joined entity with your criteria.
Upvotes: 4