如何在不向超类添加另一个实例的情况下插入子类?

How to insert to subclass without add another instance to superclass?

我使用标准的 JpaRepository 接口和 类。

我有这个类:

用户:

@Entity
@Table(name = "user")
@Inheritance(strategy = InheritanceType.JOINED)
public class User extends BaseEntity {

    private Long id;
    //Other Attr

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }
    //Getters & Setters...
}

医生:

@Entity
@Table(name = "doctor")
@PrimaryKeyJoinColumn(name = "id", referencedColumnName="id")
public class Doctor extends User {

    private Long regNumber;
    //Getters & Setters
}

我正在搜索,似乎 jpa/hibernate 没有 function/procedure 用于插入包含现有用户信息的医生。

我试图用来自用户查询的信息保存医生,它为用户创建了一个新的用户条目 table。

理论上,不是医生也可以是用户,以后可以成为医生。

In theory, one can be an user without being a doctor, later one can become doctor.

在现实生活中确实如此,但 Java 继承并非如此:给定类型的对象不能成为另一种类型的对象。如果你想模拟那种情况,继承是不好的工具。

您应该改用组合。用户可以具有医生角色。这是一个 OneToOne 关联,可以使用与您用来映射继承的相同表进行映射,并允许用户成为医生。

这也是更好的设计,因为它允许多个角色:例如,用户是医生和音乐家。继承也无法做到的事情。