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

无需@Entity与@Table注解,如何编写返回JSON的数据库查询代码?

不使用@Entity/@Table注解,用自定义类接收数据库查询结果并返回JSON

你的代码是否可行?

直接用你写的代码是不可行的。Spring Data JPA默认无法自动将原生查询的结果映射到未标注@Entity的自定义类(比如你的CustomResponse),运行时会抛出结果转换异常。

可行的实现方案

方案1:JPQL构造函数映射(推荐)

使用JPQL的NEW关键字,直接在查询中调用CustomResponse的构造函数(注意要写全类名),同时将nativeQuery设为false:

@Query(value = "SELECT NEW com.yourpackage.CustomResponse(m.name, m.count) FROM mytable m", nativeQuery = false)
List<CustomResponse> getData();

要求:CustomResponse必须有对应参数的构造函数(你的代码里已经用@AllArgsConstructor生成,满足要求)。

方案2:原生SQL配合结果集映射

如果必须使用原生SQL,可以通过@SqlResultSetMapping和@ConstructorResult指定映射规则:

  1. 先定义一个空的@Entity类(仅用于标识JPA可处理,无需映射数据库表):
@Entity
public class DummyEntity {}
  1. 在Repository方法上添加映射配置:
@SqlResultSetMapping(
    name = "CustomResponseMapping",
    classes = @ConstructorResult(
        targetClass = CustomResponse.class,
        columns = {
            @ColumnResult(name = "name", type = String.class),
            @ColumnResult(name = "count", type = Integer.class)
        }
    )
)
@Query(value = "SELECT name, count FROM mytable", nativeQuery = true)
List<CustomResponse> getData();

方案3:手动转换结果集

通过EntityManager执行原生查询,手动将结果数组映射到CustomResponse:

@Autowired
private EntityManager em;

public List<CustomResponse> getData() {
    List<Object[]> rawResults = em.createNativeQuery("SELECT name, count FROM mytable").getResultList();
    return rawResults.stream()
        .map(row -> new CustomResponse((String) row[0], (Integer) row[1]))
        .collect(Collectors.toList());
}

最终返回JSON

只要你的Controller方法返回List<CustomResponse>,Spring MVC会自动将其序列化为你期望的JSON格式:

[
  {   
    "name" : "myname",
    "count": 5 
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:02:03