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

如何通过使用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()]));

标签:java,java-ee,jpa-2-0,criteria-api,jpa-2-1
来源: https://codeday.me/bug/20190706/1398291.html