我的问题与更改保留其 ID 的实体的类型非常相似,但我使用的是 InheritanceType.JOINED 而不是 Table_per_class。
这意味着我不更改任何表,只是创建一个新的子类,其 id 与超类相同。
总而言之,我有一个 Person 类和一个 Doctor,它扩展了 Person 并具有相同的 id。我需要从数据库中检索一个 Person 并将其设置为 Doctor,保留 Person 实体中的所有数据,但为 Doctor 创建一些额外的数据。
尝试合并医生会生成一个新 ID,这对我无效。
这是我首先尝试过的
private Person getDoctor(Person person) {
// Person already a doctor ==> OK
if (person instanceof Doctor) {
return person;
}
// Transient Person ==> //Transient Doctor OK
if (person == null) {
return new Doctor();
}
// Creates a Doctor from the person (only setting id...),
// and merges it ==>
fails as the id changes.
Doctor doctor = new Doctor(person);
return personDAO.merge(doctor);
}
sorry guys,first time here.
Here´s the code above:
private Person getDoctor(Person person) {
//Person already a doctor ==> OK
if (person instanceof Doctor) {
return person;
}
//Transient Person ==> //Transient Doctor OK
if (person == null) {
return new Doctor();
}
//Creates a Doctor from the person (only setting id...), and merges it ==> fails as the id changes.
Doctor doctor = new Doctor(person);
return personDAO.merge(doctor);
}
@Inheritance(strategy = InheritanceType.JOINED)
@Entity
public class Person{
}
@Entity
public class Doctor extends Person{
public Doctor(Person person) {
if (person != null) {
this.setId(person.getId());
}
}
}