【问题标题】:Spring data jpa: Add a where clause on a projection fieldSpring data jpa:在投影字段上添加 where 子句
【发布时间】: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


【解决方案1】:

你不能在投影上这样做。只需在查询中添加 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

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2021-06-01
    • 2021-12-24
    • 2016-04-29
    • 2015-09-20
    • 2016-11-26
    相关资源
    最近更新 更多