Take the 2-minute tour ×

Have a simple object model made up of 5 entities:

  1. Company
  2. Organization
  3. Address
  4. Club
  5. Group

Shows Company, Club, and Group are all associated to Organization enter image description here

A Company is associated with a single Organization. (Group and Club are also associated with a single Organization - these are unidirectional, meaning the Organization does not contain a reference to its owner). An Organization may have 0 or more Address(es).

A subquery can be used to access Company objects based on a specific zipcode, which is an attribute of an Address. Here is a JPQL query that can access those companies with a specific zipcode.

@Query("select p from Company p, Organization org where (p.organization = org.id) and exists ( select 1 from Address ad where zipcode = :zipcode and ad.organization = org.id)")

How can the same thing be done using the JPA Criteria API?

share|improve this question

1 Answer 1

This will select companies with provided zipcode using inner join, is this what you wanted?

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Company> cq = cb.createQuery(Company.class);
Root<Organization> root = cq.from(Organization.class);
Join<Organization, Address> adr = root.join("addresses");
cq.where(cb.equal(adr.get("zipcode"), zipcode));

You won't be able to access Company via Organization, if it doesn't have a property for it. If your Company have a reference to Organization, then you can make unidirectional mapping to bidirectional mapping adding following code to Organization class:

@OneToOne(mappedBy="organization") //Providing the name of property in Company 
private Company company;
share|improve this answer
JMelnik - thanks for your response, When I run the code the following shows: The method select(Selection<? extends Company>) in the type CriteriaQuery<Company> is not applicable for the arguments (Path<Object>) Keep in mind (my update) in that there is no reference from Organizaton to Company. Thanks again. –  John Kroubalkian Jun 4 '12 at 15:36
I edited my answer, try checking. –  JMelnik Jun 4 '12 at 19:43
JMelnik, can you do this within a spring-data Specification? (org.springframework.data.jpa.domain.Specification<Organization>) –  John Kroubalkian Aug 21 '12 at 15:21
Sorry I am not aware of spring-data, please try applying this example to your case on your own. –  JMelnik Aug 22 '12 at 8:30

Your Answer


