Spring JPA自定义联表查询返回Java Record投影的分页流转换异常
解决Spring JPA Record投影转换错误问题
问题原因
当JPQL查询直接返回字段列表时,Spring Data JPA默认会将结果封装为TupleBackedMap,而Java Record无法直接通过该类型转换,导致抛出No converter found capable of converting...错误。
解决方案
修改JPQL查询,显式调用Record的全参构造器来创建投影实例,让JPA直接返回Record对象而非Map。
修改后的仓库代码
interface xRepository { @Query(""" SELECT new com.x.Tables$Projection( tableA.locationCode, tableA.referenceNumber, tableA.excerpt1, tableA.excerpt2, tableA.excerpt3, tableA.contractNumber, tableA.date, tableB.contractType, tableB.type, tableB.code ) FROM Tables$TableA tableA JOIN Tables$TableB tableB ON tableA.locationCode =tableB.locationRef AND tableA.referenceNumber=tableB.referenceNo WHERE tableA.x = 'true' AND tableB.y = 'false' AND tableB.z IS NOT NULL """) Stream<Tables.Projection> streamProjection(Pageable pageable); }
关键注意事项
- 确保Record的全参构造器参数顺序与JPQL中
SELECT new后的字段顺序完全一致,类型也要严格匹配 - JPQL中必须使用Record的全限定类名(例如
com.x.Tables$Projection),避免类路径解析错误 - Record作为投影无需添加
@Column注解,仅需保证构造器参数与查询返回字段对应即可
内容的提问来源于stack exchange,提问作者yaserso
相关产品推荐
相关产品推荐

