You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3中@Query注解传参时DTO投影返回空对象问题排查

问题解决方案

核心问题分析

  1. DTO构造函数类型不匹配:Profile实体的id是Long类型,但Pr_Profile的构造函数第一个参数是int,JPA无法自动完成类型转换,导致无法实例化DTO对象,最终返回null。
  2. 查询语句未指定投影逻辑:原查询返回完整的Profile实体,JPA没有默认规则将实体映射到自定义DTO,必须显式指定构造函数和所需字段。

具体修复步骤

1. 修正Pr_Profile构造函数的参数类型

将构造函数的id参数类型从int改为Long,与实体类的id类型保持一致:

class Pr_Profile{
    private Long id;
    private String login;
    private LocalDate birthdate;

    // 修正参数类型为Long
    public Pr_Profile(Long id, String login, LocalDate birthdate){
        this.id = id;
        this.login = login;
        this.birthdate = birthdate;
    }
}

2. 修改Repository的JPQL查询语句

在查询中显式调用Pr_Profile的构造函数,并传入需要的字段,注意要使用DTO的完整包路径类名:

interface ProfileRepository extends JpaRepository<Profile, Long>{
    @Query("SELECT new com.yourpackage.Pr_Profile(p.id, p.login, p.birthdate) FROM Profile p WHERE p.id = ?1")
    Pr_Profile fromEntityToDTO(Long id);
}

注意:将com.yourpackage替换为Pr_Profile实际所在的包路径,例如com.example.dto.Pr_Profile。

3. 可选:使用命名参数写法

如果偏好命名参数风格,可添加@Param注解:

interface ProfileRepository extends JpaRepository<Profile, Long>{
    @Query("SELECT new com.yourpackage.Pr_Profile(p.id, p.login, p.birthdate) FROM Profile p WHERE p.id = :id")
    Pr_Profile fromEntityToDTO(@Param("id") Long id);
}

内容的提问来源于stack exchange,提问作者IRahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 04:41:06