基本上我想要公司和个人的地址。地址是单独的实体。
公司可以拥有一个AddressContext,它使用与Indivuduals AddressContext相同的Address实体
AddressContext给出与个人有关的地址,例如“我的家庭地址”
java classes:
public class Address {
}
public class AddressContext {
private Address address;
private String name;
}
public class Individual {
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<AddressContext> addresseContexts;
}
public class Company {
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<AddressContext> addresseContexts;
}
必需的数据库address_context数据库表
CREATE TABLE `address_Context` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
'address_id bigint(20) NOT NULL,
'RELATED_ITEM_ID bigint(20) NOT NULL,
'RELATED_ITEM_TYPE varchar(50) NOT NULL,
'NAME' varchar(5)
);
基本上有以下
1, 1, 1, Individual, 'John's House';
2, 2, 1, Company, 'Depoy';
实际发生的是正在创建单独的表
companies_address_contexts
individuals_address_contexts
以上可能吗?我不想将AddressContext子类化为
提前致谢
答案 0 :(得分:1)
您不希望将特定地址限制为实体类型(个人/公司)。想想自雇人士将其家庭住址用作公司地址的(边缘)案例。或者多租户单元转换为办公楼的情况。你得到了要点 - 地址应该是完全独立的实体,系统中的其他实体然后通过关联表引用它们。
在你的情况下,无论如何都生成了关联表,你只需要在你的代码中进行一些小的重构就可以使用它们(一种形式)。像这样:
@Entity
public class Address {
// address fields etc
}
@Entity
public class Individual {
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "individual_addresses",
joinColumns = { @JoinColumn(name = "individual_id", unique = true) },
inverseJoinColumns = { @JoinColumn(name = "address_id") })
private Set<Address> addresses;
}
@Entity
public class Company {
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "company_addresses",
joinColumns = { @JoinColumn(name = "company_id", unique = true) },
inverseJoinColumns = { @JoinColumn(name = "address_id") })
private Set<Address> addresses;
}