我正在研究遗留系统,它没有正确的单元测试,也没有任何一个,所以我需要非常小心我在系统中做的任何更改。
我的基本情景是: 我有一个与地址有ManyToOne关系的人,我不能改变这种关系。但是知道有些类型的地址,例如:账单地址和邮寄地址。
public class Person {
@Id
@Column(name = "PERSON_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "PERSON_NAME")
private String personName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ADDRESS_ID")
private Address address;
getters and setters
地址类
public class Address {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ADDRESS_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "STREET_1_NAME")
private String street1Name;
@Column(name = "STREET_2_NAME")
private String street2Name;
getters and setters
我正在考虑将ADDRESS_TYPE列添加到ADDRESS表中,但我正在努力实现它。我只想拥有一个类型为Address的新属性postalAddress,并使postalAddress像getPostalAddress一样简单。
答案 0 :(得分:2)
感谢Alan,您的建议有所帮助,但由于与遗留代码的兼容性,我最终使用了InheritanceType。
我的地址类现在看起来像:
@Entity
@Table(name = "ADDRESS")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="ADDRESS_TYPE",
discriminatorType=DiscriminatorType.INTEGER
)
@DiscriminatorValue("null")
public class Address {
我的邮政地址如下:
@Entity
@Table(name = "ADDRESS")
@DiscriminatorValue(value="2")
public class PostalAddress extends Address {
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = "INSURED_ID")
private Insured insured;
public void setInsured(Insured insured) {
this.insured = insured;
}
public Insured getInsured() {
return insured;
}
}
因此,对于过去插入的地址没有类型我假设为null
,为了兼容性,新的地址也将为'null',只有PostalAddress将为'2'。
我的Person类看起来像
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ADDRESS_ID")
private Address address;
@Transient
private PostalAddress postalAddress;
我知道这听起来很奇怪,但我被要求有一个关系Person 1 - N PostalAddress。
答案 1 :(得分:0)
只需添加:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "POSTAL_ADDRESS_ID")
private Address postalAddress;
这会在管理关系的Person
表中添加一个新列。
无需将ADDRESS_TYPE
添加到ADDRESS
表,因为它将是多余的。
答案 2 :(得分:0)
继我之前发表的评论之后,听起来就像你想要使用地图从人到地址一对多。
按照建议添加address_type列并创建枚举地址类型(POSTAL,BILLING):
亲自:
//there are various MapKey annotations however, without testing I think these are what you need
@OneToMany
@MapKeyEnumerated(EnumType.String) //tells Hibernate we want the type to contain BILLING/POSTAL etc rather than the ENUM ordinals (0,1 etc)
@MapKeyColumn(name ="address_type")
private Map<AddressType, Address) addresses;
public Address getPostalAddress(){
return addresses.get(AddressType.POSTAL);
}
public Address getBillingAddress(){
return addresses.get(AddressType.Billing);
}
//or even
public Address getAddress(AddressType type){
return addresses.get(type);
}