How to use the JPA API when joining many tables

This is another question:

How to use JPA API in JOIN

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<Company> criteria = criteriaBuilder.createQuery( Company.class ); Root<Company> companyRoot = criteria.from( Company.class ); Join<Company,Product> products = companyRoot.join("dentist"); Join<Company, City> cityJoin = companyRoot.join("address.city");//Company->Address->City-city criteria.where(criteriaBuilder.equal(products.get("category"), "dentist"),    criteriaBuilder.equal(cityJoin.get("city"),"Leeds")); 

The company has an address within which there is City-pojo and Country-Pojo. How can I use it in JOIN ? I tried to reference it using address.city , but I got an error:

The [address.city] attribute from the managed type [EntityTypeImpl @ 1692700229: Company [javaType: class com.test.domain. Computer descriptor: RelationalDescriptor (com.test.domain.Company → [DatabaseTable (COMPANY)]), associations: 16] ] no.

+10
java join jpa criteria-api
Jan 26 '12 at 20:55
source share
1 answer

If you use the canonical Metamodel , you will avoid such errors. In your code, you incorrectly used the keyword "dentist", which is probably the reason for your mistake, because "dentist" is not a field in the essence of the company.

However, looking at how you defined your class in another question, a way to determine if join with Metamodel:

 SetJoin<Company,Product> products = companyRoot.join(Company_.products); 

As you can see, Metamodel avoids the use of strings and thus avoids a lot of runtime errors. If you are not using Metamodel anyway, try the following:

 SetJoin<Company,Product> products = companyRoot.join("products"); 

If you want to add predicate , i.e. something after where , you will write something like:

 Predicate predicate = criteriaBuilder.equal(products.get(Product_.category), "dentist"); criteria.where(predicate); 

If you want to add join for City object:

 Join<Company, City> city = companyRoot.join(Company_.city); predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(city.get(City_.cityName), "Leeds"); criteria.where(predicate); 

(suppose the cityName field is the correct field name for your city).

+19
Jan 26 2018-12-12T00:
source share



All Articles