【问题标题】:Spring JPA projection problem with subquery带有子查询的 Spring JPA 投影问题
【发布时间】:2020-07-26 10:41:26
【问题描述】:

我正在使用 JPA 投影,但是当我的查询包含子查询时它会失败。 例如:

public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_id")
    private Long id;

    private String name;

}

投影界面如下:

public interface StudentProjection {
    Integer getId();
}

和存储库:

@Query("select s from Student s where s.id = 88831")
List<StudentProjection> findProjections();

使用此代码一切正常,并且 repo 返回一个 EleveProjection 列表。

但如果我将查询更改为此(即通过子选择获取 id - 仅作为示例):

@Query("select s from Student s where s.id = (select max(88831) from Student)")
List<StudentProjection> findProjections();

...方法findProjections()返回org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap的列表强>

显然不可能在这个对象上执行 getId() (抛出异常)。

它看起来像 Spring data JPA 中的一个错误。 我目前使用的是 2.2.4.RELEASE 版本。

关于如何使用 JPA 投影的子查询有什么想法吗?

谢谢

【问题讨论】:

  • 我已经在 Spring Jira 上提交了测试用例。我是bug,我会测试ticket cmets中给出的解决方法。

标签: java spring-boot spring-data-jpa subquery projection


【解决方案1】:

@Query 的内容尊重 Jpql 规范,因此与 Spring 数据无关。

试试这个 @Query("select s from Student s where s.id in (select max(88831) from Student)") List<StudentProjection> findProjections();

AFAIK 你可以在 jpql 中使用带有子查询的子句 existsin...

【讨论】:

  • 为什么不只是 select s.id from Student s where s.id.... ?您的投影需要的是 id ...
  • 我已经为示例进行了简化。在现实生活中,学生投影有 10 - 12 个字段。
  • 你试过用原生的吗? -> @Query("select id from Student where id in (select max(88831) from Student), nativeQuery=true)
  • 使用仅检索 id 的本机查询,JPA 将返回整个对象 Student ?
  • 不只是你需要的......所以这里是你的例子id
猜你喜欢
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
相关资源
最近更新 更多