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

Spring Boot JPA返回正确计数但无数据问题排查

问题解决方法

核心原因与修复

返回空对象数组的本质是JSON序列化无法读取实体类的属性值——Spring默认使用Jackson进行JSON转换,它需要通过getter方法访问对象的私有属性,而你的Book实体类仅定义了私有字段和构造方法,未提供对应getter方法。

修复后的Book实体类代码

为每个私有字段添加getter方法:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;

@Entity
public class Book {
  
  @Id
  @GeneratedValue
  private Long id;
  
  private String name;
  private String author;
  private BigDecimal price;

  public Book() {}

  public Book(String name, String author, BigDecimal price) {
    this.name = name;
    this.author = author;
    this.price = price;
  }

  // 添加所有属性的getter方法
  public Long getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public String getAuthor() {
    return author;
  }

  public BigDecimal getPrice() {
    return price;
  }
}

可选简化方案

若不想手动编写大量getter方法,可使用Lombok的@Getter注解自动生成:

  1. 在pom.xml(Maven)或build.gradle(Gradle)中添加Lombok依赖
  2. 在Book类上添加@Getter注解:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;
import lombok.Getter;

@Entity
@Getter // 自动生成所有私有字段的getter方法
public class Book {
  
  @Id
  @GeneratedValue
  private Long id;
  
  private String name;
  private String author;
  private BigDecimal price;

  public Book() {}

  public Book(String name, String author, BigDecimal price) {
    this.name = name;
    this.author = author;
    this.price = price;
  }
}

额外检查点

添加getter后仍有问题时,可排查以下两点:

  • 检查数据库表列名与实体类字段名是否匹配(例如数据库列是book_name但实体类是name,需添加@Column(name = "book_name")注解映射)
  • 确认实体类字段是否正确注入了数据库数据(可通过控制台打印的books对象,查看toString输出是否包含属性值;若toString也为空,需检查Repository或数据库数据是否正常)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:26:28