JPQL ManyToMany select

gtgaxiola picture gtgaxiola · Sep 14, 2012 · Viewed 20.1k times · Source

I have a Many To Many relationship between two entities called: Car and Dealership.

In native MySQL I have:

car (id and other values)
dealership (id and other values)
car_dealership  (car_id and dealership_id)

And the query I want to make in JPQL is:

#Select List of cars in multiple dealerships
SELECT car_id FROM car_dealership WHERE dealership_id IN(1,2,3,56,78,999);

What is the proper way to make the JPQL equivalent?

My Java method signature is:

public List<Car> findByDealership(List<Dealership> dealerships);

I have tried

    //TOTALLY WRONG QUERY CALL!!!     
    Query query = em.createQuery("SELECT c FROM Car c WHERE :dealer_ids IN c.dealerships");
    List<Long> dealerIds = new ArrayList<Long>();
    for(Dealership d : dealerships) {
        dealerIds.add(d.getId());
    }
    query.setParameter(":dealer_ids", dealerIds); 
    List<Dealership> result = (List<Dealership>) query.getResultList();
    return result;
}

Here is my JPA Annotations for such relationship in java:

@Entity
@Table(name = "car")
public class Car implements Serializable {

     //Setup of values and whatnot....
     @ManyToMany
     @JoinTable(name = "car_dealership", joinColumns =
     @JoinColumn(name = "car_id", referencedColumnName = "id"),
     inverseJoinColumns = @JoinColumn(name = "dealership_id", referencedColumnName = "id"))
     private List<Dealership> dealerships;

     ... other stuff (getters/setters)

}

@Entity
@Table(name = "property")
public class Dealership implements Serializable {

    //Setting of values and whatnot

    @ManyToMany(mappedBy = "dealerships")
    private List<Car> cars;

    .... other stuff(getters/setters)

}

EDIT

I also have tried:

 Query query = em.createQuery("SELECT c FROM Car c INNER JOIN c.dealerships d WHERE d IN (:deals)");
 query.setParameter("deals", dealerships);

Which threw the Error:

org.eclipse.persistence.exceptions.QueryException

Exception Description: Object comparisons can only use the equal() or notEqual() operators.  
Other comparisons must be done through query keys or direct attribute level comparisons. 

Expression: [
Relation operator [ IN ]
Query Key dealerships
  Base stackoverflow.question.Car
Constant [
Parameter deals]]

Answer

JB Nizet picture JB Nizet · Sep 14, 2012
select car from Car car 
inner join car.dealerships dealership
where dealership in :dealerships

The parameter must be a collection of Dealership instances.

If you want to use a collection of dealership IDs, use

select car from Car car 
inner join car.dealerships dealership
where dealership.id in :dealershipIds

Remamber that JPQL always use entities, mapped attributes and associations. Never table and column names.