user2035039
user2035039

Reputation: 971

JPA Specifications: Select items where list attribute contains item with certain value

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 Persons, 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

Answers (1)

yntelectual
yntelectual

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

Related Questions