gpt4 book ai didi

java - Hibernate多态性(扩展父类)

转载 作者:行者123 更新时间:2023-12-02 08:29:49 25 4
gpt4 key购买 nike

关于 Hibernate 多态性和扩展父类(我不能直接修改)的问题。我的父类名为Contact:

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

子类称为 ContactLocation,它将 LocationContact 相关联:

@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);
}
}

如何使用我的 ContactLocationDaocontact_location 表中创建一行,将 Contact 映射到 Location

最佳答案

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

关于java - Hibernate多态性(扩展父类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3720838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com