我想将JPA CriteriaBuilder用于多个表列上的LEFT JOIN FETCH。
我有两个具有不同组合键的实体:
@Embeddable
public class CarKey {
private String CarType;
private String CarId;
}
@Entity(name = "cars")
public class Car {
@EmbeddedId
private CarKey key;
// car information
@OneToMany
private Set<Part> parts;
}
@Entity (name = "parts")
public class Part {
@EmbeddedId
private PartKey key;
private String CarType;
private String CarId;
// part information
}
HQL等效项应类似于:
SELECT c
FROM cars c
LEFT JOIN FETCH parts p
ON c.key.CarType = p.CarType
AND c.key.CarId = p.CarId
我的CriteriaQuery如下:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Car> carQuery = cb.createQuery(Car.class).distinct(true);
Root<Car> carRoot = carQuery.from(Car.class);
carQuery.select(carRoot);
carRoot.fetch("parts", JoinType.LEFT);
如何指定JOIN列?它们由一个复合键组成。我尝试将Fetch强制转换为Join并应用.on(...),该操作不起作用,因为“ fetch join中不允许with子句”。对于LEFT JOIN,在WHERE子句中定义匹配项无效。