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

Spring Data JPA调用save()字段丢失问题排查求助

问题原因与解决方案

这是因为你的父类BaseClass没有被JPA识别为持久化映射的超类,导致子类继承的phone、other字段没有被JPA纳入持久化管理,所以save操作时不会将这些字段写入数据库。而子类重写字段后,这些字段属于子类自身的持久化字段,自然能被正常保存。

解决方法

给父类BaseClass添加@MappedSuperclass注解,这个注解的作用就是告诉JPA:这个类是一个映射超类,它的字段会被所有继承它的实体类继承并映射到对应的数据库表中。

修改后的代码示例

  1. 父类BaseClass:
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public class BaseClass {
    private String phone;
    private String other;

    // 省略getter、setter方法
}
  1. 子类User(Other类同理):
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User extends BaseClass {
    @Id
    private Long id;

    // 省略getter、setter方法
}
  1. 对应的Repository接口:
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {
}

验证修改

重新运行应用,调用repository.save()方法插入数据后,再查询数据库:

> select * from user;
id phone other
1  138xxxxxxx  test

此时phone和other字段会被正常写入数据库,同时你也不需要在每个子类中重复定义这些字段,达到了代码复用的目的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:32:19