我的问题非常类似于更改保留其 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());
}
}
}
就像您链接到的问题一样,答案是“您无法使用 Hibernate API 执行此操作”。
原因实际上很清楚 - Hibernate 的目标是使持久性尽可能透明,因此,不能允许您使用持久对象做一些普通 Java 对象无法做的事情。一旦你创建了一个实例Person
(在普通的java中),它总是Person
。它永远不会是Doctor
。你能做的最好的事情就是创建一个Doctor
实例和副本Person
的属性。
然而,与普通 java 不同的是,使用 Hibernate,您可以作弊并实现您想要的:-),但它必须通过本机 SQL 来完成。在您的方法中,您需要:
- Evict
Person
来自会话的实例(以及二级缓存,如果适用)
- 插入具有匹配 ID 的行(取自
Person
实例)进入Doctors
桌子。这是必须作为本机 sql 完成的部分,但您可以将其定义为命名查询并将上面的 id 设置为参数。请注意,如果有任何限制Doctor
属性,您需要确保插入的值满足它们。
- Reload
Person
实例 - 现在将被加载为Doctor
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)