有关休眠多态性和扩展父类(我不能直接修改)的问题。我的父班叫Contact:

@Entity
@Table(name="contact")
@Inheritance(strategy=InheritanceType.JOINED)
public class Contact {
  @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  public long id;
  public String name;
}


子类称为ContactLocation,它将位置与联系人相关联:

@Entity
@Table(name="contact_location")
@Inheritance(strategy=InheritanceType.JOINED)
public class ContactLocation extends Contact {
  @ManyToOne(targetEntity=Location.class, cascade=CascadeType.ALL)
  Location location;
}


结果数据库表结构似乎是正确的:

contact:
 id:long
 name:varchar

contact_location:
 contact_id:long
 location_id:long


这是我的保存方法,我需要更新现有的ContactLocation或为现有的联系人保存新的ContactLocation:

public void saveContact(Object dialog) {
  Contact contact = ui.getAttachedObject(dialog, Contact.class);
  ContactLocation contactLocation = null;
  if (contact instanceof ContactLocation) {
     LOG.debug("Casting Contact to ContactLocation");
     contactLocation = (ContactLocation)contact;
     //TODO Update existing ContactLocation
     //UPDATE contact_location SET location_id = 33 WHERE contact_id = 22;
  }
  else {
     LOG.debug("Contact NOT instanceof ContactLocation");
     //TODO Save new ContactLocation from existing Contact
     //INSERT INTO contact_location (contact_id, location_id) VALUES (22,33);
  }
}


如何在contact_location表中创建一行,以使用ContactLocationDao将联系人映射到位置?

最佳答案

我知道,创建对象后不支持更改类型。恐怕您必须创建一个新的ContactLocation对象,更新可能的引用,然后删除原始的Contact。

10-04 11:04