我有以下模型, Person 是 Patient 和 Practitioner 的超类。Person 对象可以被实例化,但是它们可以在以后更改为 Practitioner 或 Patient,但是在转换为子类对象时,Hibernate 会在 person 表中创建一个新行。这是我的班级陈述。我在 Person 类上使用复制构造函数在转换时用当前的 person 对象实例化子类对象。
@Entity
@Table(name="person")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person extends BasePerson{
private Set<MedicalAidCard> medicalAidCards = new HashSet<MedicalAidCard>();
public Person() {
}
public Person(Person person) {
this.setActive(person.getActive());
this.setCity(person.getCity());
this.setCountry(person.getCountry());
this.setCreatedBy(person.getCreatedBy());
this.setDateCreated(person.getDateCreated());
this.setDateModified(person.getDateModified());
this.setDateOfBirth(person.getDateOfBirth());
this.setFirstName(person.getFirstName());
this.setGender(person.getGender());
this.setId(person.getId());
this.setLastName(person.getLastName());
this.setMaritalStatus(person.getMaritalStatus());
this.setMiddleName(person.getMiddleName());
this.setModifiedBy(person.getModifiedBy());
this.setRace(person.getRace());
this.setTitle(person.getTitle());
this.setVersion(person.getVersion());
}
@JsonIgnore
@ManyToMany
@JoinTable(name="card_person", joinColumns=@JoinColumn(name="person_id"),
inverseJoinColumns=@JoinColumn(name="card_id"))
public Set<MedicalAidCard> getMedicalAidCards() {
return medicalAidCards;
}
public void setMedicalAidCards(Set<MedicalAidCard> medicalAidCards) {
this.medicalAidCards = medicalAidCards;
}
@Transient
public Boolean getPatient(){
return this instanceof PersonPatient;
}
}
请注意,BasePerson 是一个包含基本人口统计信息的 @MappedSuperClass
@Entity
@PrimaryKeyJoinColumn(name = "id")
@Table(name="patient")
public class PersonPatient extends Person{
private String fileNumber;
private String oldFileNumber;
private Date dateRegistered;
public PersonPatient() {
}
public PersonPatient(Person person) {
super(person);
}
@Column(name="file_number",unique=true)
public String getFileNumber() {
return fileNumber;
}
public void setFileNumber(String fileNumber) {
this.fileNumber = fileNumber;
}
@Temporal(TemporalType.DATE)
@Column(name="date_registered")
public Date getDateRegistered() {
return dateRegistered;
}
public void setDateRegistered(Date dateRegistered) {
this.dateRegistered = dateRegistered;
}
@Column(name="old_file_number")
public String getOldFileNumber() {
return oldFileNumber;
}
public void setOldFileNumber(String oldFileNumber) {
this.oldFileNumber = oldFileNumber;
}
@Override
public String toString() {
return super.getId().toString();
}
}
顺便说一句,我使用 SpringData CrudRepository 方法进行保存,而 Hibernate 是我的 JPA 提供者。我曾想过删除当前人,但我意识到如果当前人已经代表另一个子类,它就行不通了。