Tôi có mối quan hệ Nhiều đến Nhiều giữa hai thực thể được gọi là: Ô tô và Đại lý.JPQL ManyToMany chọn
Trong MySQL mẹ đẻ tôi có:
car (id and other values)
dealership (id and other values)
car_dealership (car_id and dealership_id)
Và truy vấn Tôi muốn làm trong JPQL là:
#Select List of cars in multiple dealerships
SELECT car_id FROM car_dealership WHERE dealership_id IN(1,2,3,56,78,999);
cách thích hợp để làm cho JPQL tương đương là gì?
My Java phương pháp chữ ký là:
public List<Car> findByDealership(List<Dealership> dealerships);
Tôi đã thử
//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;
}
Đây là JPA Chú thích của tôi cho mối quan hệ như vậy trong 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
Tôi cũng đã cố gắng:
Query query = em.createQuery("SELECT c FROM Car c INNER JOIN c.dealerships d WHERE d IN (:deals)");
query.setParameter("deals", dealerships);
nào ném Lỗi:
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]]
cảm ơn, vui lòng xem chỉnh sửa của tôi. – gtgaxiola
Có vẻ như EclipseLink không muốn so sánh các đối tượng. Nó sẽ làm việc với Hibernate. Sử dụng gợi ý thứ hai của tôi, sau đó, so sánh ID. –
Cảm ơn ... cũng giống như một lưu ý EclipseLink không thích dấu ngoặc đơn trong phần IN (: dealershipIds) ... – gtgaxiola