0
我在2個實體之間有一個非常基本的多對多關係。JPA2標準:多對多連接表,如何對連接表進行限制
讓我們說車:
public class Car {
@Id
@Column(name = "ID")
private Long id;
@ManyToMany
@JoinTable(name = "CAR_GARAGE",
joinColumns = { @JoinColumn(name = "CAR_ID", nullable = false) },
inverseJoinColumns = { @JoinColumn(name = "GARAGE_ID", nullable = false) })
private List<Garage> listGarages;
}
和車庫:
public class Garage {
@Id
@Column(name = "ID")
private Long id;
@ManyToMany
@JoinTable(name = "CAR_GARAGE",
joinColumns = { @JoinColumn(name = "GARAGE_ID", nullable = false) },
inverseJoinColumns = { @JoinColumn(name = "CAR_ID", nullable = false) })
private List<Car> listCars;
}
我需要做一個查詢從一個車庫檢索所有汽車:
public Long getCarFromGarage(final String pGarageId) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Car> crit = builder.createQuery(Car.class);
// jointure
Root<Car> root = crit.from(Car.class);
Join<TarifEntiteFac, Garage> garageJoin = root.join("listGarages");
crit.where(builder.equal(garageJoin.get("id"), pIdentifiant));
return em.createQuery(crit).getResultList();
}
這工作正常但生成的SQL是這樣的:
SELECT c.id
FROM CAR c
INNER JOIN CAR_GARAGE cg ON c.id = cg.CAR_ID
INNER JOIN GARAGE g on cg.GARAGE_ID = g.ID
WHERE g.ID = :pGarageId
是否有JPA的方式,而不是產生這樣的:
SELECT c.id
FROM CAR c
INNER JOIN CAR_GARAGE cg ON c.id = cg.CAR_ID
INNER JOIN GARAGE g on cg.GARAGE_ID = g.ID
WHERE cg.GARAGE_ID = :pGarageId
爲了拯救自己的額外加入。
感謝您的回答,我的問題是沒有重新映射到實體的連接表,歡呼聲。 – TheBakker