如何在JPA CriteriaBuilder中使用IN

时间:2018-11-06 09:20:42

标签: java jpa

我使用JPA,并具有对象Building whit字段Owner和BuildingType。 我想在列表中找到所有者所在的所有建筑物以及特定的建筑物类型。

 List<Owner> owners;
    BuildingType type;
    CriteriaBuilder builder = getCriteriaBuilder();
    CriteriaQuery<Building> criteria = builder.createQuery(Building.class);
    Root<Building> rootBuilding = criteria.from(Building.class);
    criteria.select(rootBuilding);
    criteria.where( builder.equal( rootBuilding.get( _buildingType ), buildingType ) );

最后一行代码适用于buildingType,但适用于所有者列表呢?

1 个答案:

答案 0 :(得分:1)

说明:

  • 首先,您需要确保拥有所有者ID列表,而不是列表所有者;
  • 然后您可以同时加入所有者和BuildingType并在其上列出谓词。
  • 最后选择建筑物实体上的根

解决方案:

List<Long> ownerIds; //include Id of owners you want
BuildingType type;  //include the type you want 
CriteriaBuilder builder = getSessionFactory().getCurrentSession().getCriteriaBuilder();
CriteriaQuery < Building > criteria = builder.createQuery(Building.class);
Root < Building > myObjectRoot = criteria.from(Building.class);
Join < Building, Owner > joinOwner = myObjectRoot.join("owner");
Join < Building, BuilderType > joinBuilderType = myObjectRoot.join("buildingType");

List < Predicate > predicates = new ArrayList < Predicate > ();
predicates.add(builder.equal(joinBuilderType.get("id"), type.getId()))
predicates.add(builder.in(joinOwner.get("id")).value(ownerIds))
criteria.select(myObjectRoot);
criteria.where(builder.and(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(criteria).getResultList();