JPQL ManyToMany选择

时间:2012-09-14 13:43:13

标签: java database java-ee jpa jpql

我在两个实体之间有多对多的关系:汽车和经销商。

在原生MySQL中我有:

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

我想在JPQL中创建的查询是:

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

使JPQL等效的正确方法是什么?

我的Java方法签名是:

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

我试过了

    //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;
}

这是我在JP中的这种关系的JPA注释:

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

}

修改

我也尝试过:

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

引发了错误:

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]]

1 个答案:

答案 0 :(得分:26)

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

参数必须是经销商实例的集合。

如果您想使用经销商ID的集合,请使用

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

请记住,JPQL始终使用实体,映射属性和关联。从不使用表名和列名。