在Spring JPA/Java中使用父类的现有记录
我正在开发一个解决方案,在确定的情况下,我有一个名为Cliente的类,如下所示在Spring JPA/Java中使用父类的现有记录,java,inheritance,spring-data-jpa,h2,Java,Inheritance,Spring Data Jpa,H2,我正在开发一个解决方案,在确定的情况下,我有一个名为Cliente的类,如下所示 @Entity @Inheritance(strategy=InheritanceType.JOINED) public class Cliente implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) priva
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Cliente implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String nome;
private String email;
@ElementCollection
@CollectionTable(name="TELEFONE")
private Set<String> telefones = new HashSet<>();
public Cliente() {}
//getters and setters
}
在我的数据库中,当应用程序启动时,我有两个表。表函数和表客户。在Funcionario表中,我有一个名为“Id”的字段,它将Funcionario上的记录与Cliente上的记录相关联
当我需要在Functionario类中保存一条记录时,我需要将参数“Id”、“Nome”和“Email”传递给超级构造函数,并在Functionario表和Cliente表上创建一条新记录
到目前为止,似乎一切都进行得很顺利,但在某个时候我需要使用现有的班级客户记录。换句话说,我必须在Functionario表中插入一条新记录,但我需要使用一条已经存在于Cliente表中的记录
我搜索了很多,但没有找到有用的东西。你知道我怎样才能解决这个问题吗
非常感谢 我认为这对JPA不起作用,因为它确实与Java中继承的工作方式相矛盾。您必须加载一个
Cliente
实例,然后以某种方式将其转换为functionaio
实例
我认为有两种可能的方法可以解决这个问题
Funcionario
表中创建一些伪数据。然后加载实体,它将显示为functionaio
Funcionario
不应扩展Cliente
,而是Funcionario
应是Cliente
中可选的一对一引用。将其重命名为西班牙语(?)等价的functionariorole
可能是一个好主意,这样Cliente
可能有一个functionariorole
。这样,对函数的更改就是添加一个引用。如果共享该id,则在两个实体中,它甚至可能与同一数据库架构匹配
我想到了改变我的对象模型的可能性。但我不认为这个模型不可能实现。好吧,你澄清了我的想法!非常感谢你!!
@Entity
public class Funcionario extends Cliente{
private static final long serialVersionUID = 1L;
private String cpf;
private String cargo;
private Double salario;
private String login;
private String senha;
private String perfil;
public Funcionario() {}
public Funcionario(Integer id, String nome, String email, String cpf, String cargo, Double salario, String login, String senha, String perfil) {
super(id, nome, email);
this.cpf = cpf;
this.cargo = cargo;
this.salario = salario;
this.login = login;
this.senha = senha;
this.perfil = perfil;
}
//getters and setter
}