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

Spring Data JPA中能否使用Record作为select new语法的返回类型?

在Spring Data JPA中使用Record作为select new的返回类型

完全可以在Spring Data JPA的JPQL查询中使用Java Record作为select new语法的返回类型,核心原因是Java Record天生适配JPA对DTO的要求:它会自动生成与组件匹配的全参构造方法,同时组件的访问方法(如id()、username())也符合JPA对属性访问的规则。

示例代码

首先定义作为返回载体的Record:

public record MyRecord(Long id, String username) {}

然后在Spring Data JPA Repository中编写查询:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT new com.example.demo.MyRecord(u.id, u.username) FROM User u WHERE u.age > :age")
    List<MyRecord> findUserRecordsByAgeGreaterThan(@Param("age") Integer age);
}

关键注意点

  • 必须在select new后指定Record的全限定类名,不能省略包路径
  • Record的构造参数顺序、类型要与JPQL中select的字段顺序、类型完全匹配
  • Record不需要添加@Entity等JPA实体注解,它仅作为数据传输对象(DTO)使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:52:09