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

Spring Boot使用JPA继承时findAll返回实体哈希无法生成正确JSON问题

问题根因

返回实体类哈希码的核心原因是JSON序列化工具无法读取实体类的私有属性值,直接调用了Object.toString()方法输出对象标识,和JPA继承关联表逻辑本身无关。

修复步骤
  • 第一步:给所有实体类补全Getter/Setter方法
    所有私有属性必须提供公开的get/set方法,序列化工具才能读取属性值。推荐使用Lombok的@Data注解一键生成,无需手动编写模板代码;不使用Lombok则手动给所有属性(含父类、子类的所有私有字段)编写对应的getXxx、setXxx方法。
    示例代码:
    import lombok.Data;
    
    @Data
    @Entity(name = "Users")
    @Inheritance(strategy = InheritanceType.JOINED)
    public class UserEntity {
        // 原有属性保持不变
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int userkey;
        @Column(nullable = false, unique = true)
        private String id;
        @Column(nullable = false, length = 50)
        private String name;
        @Column(nullable = false)
        private String password;
        @Column(nullable = true)
        private String email;
    }
    
    @Data
    @Entity(name = "Account")
    public class AccountEntity extends UserEntity{
        // 原有属性保持不变
        @Column(nullable = false, unique = true)
        private String accountno;
        @Column(nullable = true)
        private String accountname;
        @Column(nullable = false)
        private int accountpw;
        @Column(nullable = false)
        private long balance;
    }
    
  • 第二步:修正集合泛型定义,避免原始类型导致的序列化异常
    修改Service层代码:
    public List<UserEntity> findAll() {
        List<UserEntity> users = UserRepository.findAll();
        return users;
    }
    
  • 第三步:优化Controller序列化逻辑,二选一即可
    方案1:直接返回对象,交给Spring MVC自动序列化(更推荐,无需手动处理JSON转换)
    @RequestMapping(value = "/getMyInfoall", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> getMemberall(@RequestBody JSONObject sendInfo) throws IOException {
        List<UserEntity> user = UserService.findAll();
        Map<String, Object> result = new HashMap<>();
        result.put("data", user);
        return result;
    }
    
    方案2:继续使用fastjson的JSONObject,确认getter齐全后即可正常序列化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:09:03