0

I use JPA and have object Building whit fields Owner and BuildingType. I want to find all the buildings where the owner is in List and specific building type.

 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 ) );

The last row of code work for buildingType, but for owner list what?

K.Nicholas
  • 10,956
  • 4
  • 46
  • 66
Radoslav
  • 75
  • 1
  • 10
  • 1
    i think you can refer [this](https://stackoverflow.com/questions/42530677/jpa-criteria-builder-in-clause-query). you should search before given a question – Truong Huy Nov 06 '18 at 09:33
  • `criteria.where(builder.and(rootBuilding.join(_owner).in(owners),builder.equal( rootBuilding.get( _buildingType ), buildingType )));` This is the answer i search for. – Radoslav Nov 06 '18 at 12:04

1 Answers1

3

Description:

  • First you need to make sure you have the list of owner ids instead of List owners;
  • then you can join on both owner and BuildingType and make the list of predicate on them.
  • finally select on the root which is on Building entity

Solution:

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();