我是两个实体之间非常基本的多对多关系。
让我说汽车:
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;
}
我需要进行查询以从一个车库检索所有CAR:
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
为自己节省额外的加入次数。
答案 0 :(得分:0)
我没有看到如何强制只使用多对多关系的单个连接,除非有一些查询提示或提供者特定选项可以启用此优化。
但是,您也可以通过将中间表映射为实体并向此实体添加其他onetomany映射来生成单个连接。