我尝试使用带有连接列条件的 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);
但似乎我们不能将规格和预测混为一谈。
关于如何做到这一点的任何想法?谢谢:)
你不能在投影上这样做。只需在查询中添加 WHERE 子句,如下所示:
List<CarProjection> findByColor_Label(String label);
它可能不会在连接中添加 where 子句,而是在 - 将其应用于整个查询之后。但最终结果应该是相同的。
文档:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions