我使用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,但适用于所有者列表呢?
最佳答案
描述:
首先,您需要确保拥有所有者ID列表,而不是列表所有者。
那么您可以同时加入owner和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();