我使用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,但适用于所有者列表呢?
答案 0 :(得分:1)
说明:
解决方案:
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();