简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM