Hibernate多态性(扩展父类)

时间:2010-09-15 18:57:43

标签: java hibernate orm polymorphism

有关Hibernate Polymorphism和扩展父类的问题(我可以直接修改)。我的父类名为 Contact

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

子类名为 ContactLocation ,它将 Location Contact 相关联:

@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 联系映射到位置

1 个答案:

答案 0 :(得分:2)

我知道创建后不支持更改类型的对象。您将不得不创建一个新的ContactLocation对象,更新可能的引用,然后删除原始的联系人,我担心。