我有两个实体之间的多对多关系,它们分别是:汽车和经销商。
在本机 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;
}
这是我在Java中使用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]]