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注解自动生成:
- 在
pom.xml(Maven)或build.gradle(Gradle)中添加Lombok依赖 - 在
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
相关产品推荐
相关产品推荐

