【发布时间】:2017-04-05 13:25:06
【问题描述】:
我尝试在连接列上使用带有条件的 Spring 数据 JPA 投影,但没有成功。
给定以下类:
interface CarProjection {
String getName();
List<String> getColorsLabel();
}
class Car{
String name;
@OneToMany(mappedBy = "car")
List<Color> colors;
}
class Color{
String label;
@ManyToOne
Car car;
}
以及以下存储库方法:
List<CarProjection> findAllBy();
一切正常,spring 生成以下查询:
[....] left outer join color colors1_ on car0_.id=colors1_.car_id
我要做的是在这个连接上添加一个 where 子句,例如:
[....] left outer join color colors1_ on (car0_.id=colors1_.car_id AND colors1_.location='EXTERIOR')
在投影类上,它会给出类似:
interface CarProjection {
String getName();
@Where("label=='EXTERIOR'")
List<String> getColorsLabel();
}
我知道我可以在 @Value 中使用 spel 表达式来执行此操作,但是 spring 将获取实体的所有列,而不仅仅是投影的列(开放投影)。
我还尝试将 JPA 规范与我的存储库中的投影相结合:
List<CarProjection> findAllBy(Specification<CarProjection> specification);
但似乎我们不能混合规格和预测。
关于如何做到这一点的任何想法?谢谢:)
【问题讨论】:
-
FWIW Spring 不生成任何查询。您的 JPA 提供程序会这样做。
标签: spring hibernate jpa spring-data spring-data-jpa