Radoslav
Radoslav

Reputation: 75

How to use IN with JPA CriteriaBuilder

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?

Upvotes: 0

Views: 550

Answers (1)

Mohammadreza  Alagheband
Mohammadreza Alagheband

Reputation: 2230

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

Upvotes: 3

Related Questions