2

我正在研究一个遗留系统,它没有适当的单元测试,也没有,所以我需要非常小心我在系统中所做的任何更改。

我的基本情况是:我有一个与 Address 有 ManyToOne 关系的 Person,我无法改变这种关系。但要知道地址有多种类型,例如:帐单地址和邮寄地址。

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 表中,但我正在努力解决如何实现它。我只想拥有一个地址类型的新属性 postalAddress,并像 getPostalAddress 一样简单地获取 postalAddress。

4

3 回答 3

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 建立关系。

于 2013-10-16T21:41:13.030 回答
0

必须添加:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "POSTAL_ADDRESS_ID")
private Address postalAddress;

这将在Person管理关系的表中添加一个新列。无需添加ADDRESS_TYPEADDRESS表中,因为它将是多余的。

于 2013-10-15T16:59:20.337 回答
0

除了我之前的评论之外,我觉得你想要使用地图从人到地址的一对多。

按照您的建议添加 address_type 列并创建一个 Enum AddressType (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);
}
  • 我假设地址表对人员有一个 FK。
于 2013-10-15T18:30:15.983 回答