如何通过使用Criteria API将其子实体的属性列入白名单来选择JPA实体?

我坚持以下假设问题:

使用Criteria API(而不是JPQL),并给出

>一个充满用户的桌子,每个用户都有多辆车

@Entity 
public class User {
    @Id 
    private Long     id;

    @OneToMany 
    private Set<Car> cars;
}
@Entity 
public class Car {
    @Id 
    private Long id;

    private String model;
}

> A Set< String>含车型:

Set<String> models = getThousandsOfModels();

How can I select the Users having at least one Car whose model is in the models Set ?

我已经阅读了很多SO答案,尝试了不同的方式(最有希望的似乎是使用Expression< Collection< String>>创建谓词,使用.in()等)但是没有任何效果.

最佳答案 以下代码可以解决问题:

Set<String> models = getHundredsOfModels(); 
if (models.size()>1000) throw new TooManyResultsException(); // Oracle limit

CriteriaBuilder cb          = em.getCriteriaBuilder();
CriteriaQuery<User> cQuery  = cb.createQuery(User.class);
Root<User> user             = cQuery.from(User.class);
List<Predicate> predicates  = new ArrayList<Predicate>();

//  This lines are the trick  ------------------------------------------
Join<User, Car> usersCars   = user.join("cars", JoinType.INNER);
Predicate p                 = usersCars.<String>get("model").in(models);
// ---------------------------------------------------------------------    

predicates.add(p);
cQuery.select(user).where(predicates.toArray(new Predicate[predicates.size()]));
点赞