如何通过JPA注释将不同的国家/州代码映射到基础实体?

时间:2018-05-06 18:09:21

标签: java jpa orm jpa-2.0 jpa-2.1

我有一个包含以下字段的实体:

private Date dateOfBirth;
private String cityOfBirth;
private Long birthStateCodeId;
private Long birthCountryCodeId;
private Boolean isUSCitizen;
private Long citizenshipCountryCodeId;
private String address1;
private String address2;
private String addressCity;
private Long addressStateCodeId;
private Long addressCountryCodeId;
private String postalCode;

从上面的代码片段可以看出,我有

  • 我使用StateCodes表中的州代码和
  • 的2个属性( birthStateCodeId addressStateCodeId
  • 我使用CountryCodes表中的国家/地区代码的3个属性( birthCountryCodeId,citizenshipCountryCodeId addressCountryCodeId )。

使用JPA(将Hibernate作为持久性提供程序),如何将上述5个属性(2个州代码和3个国家/地区代码)映射到两个单独的表StateCodes和CountryCodes?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

@Entity
public class PersonIdentification {
    // primary key
    @Id // and other annotations, see JPA Spec or tutorials
    private long id;

    // regular attributes
    private Date dateOfBirth;
    private String cityOfBirth;
    private Boolean isUSCitizen;
    private String address1;
    private String address2;
    private String addressCity;
    private String postalCode;

    @ManyToOne
    private StateCode birthStateCode;
    @ManyToOne
    private StateCode addressStateCode;

    @ManyToOne
    private CountryCode birthCountryCode;
    @ManyToOne
    private CountryCode addressCountryCode;
    @ManyToOne
    private CountryCode citizenshipCountryCode;

    // setter & getter methods as needed...
}

接下来,为“代码”类型定义实体类:

@Entity
public class StateCode {
    // primary key
    @Id // and other annotations, see JPA Spec or tutorials
    private long id;

    private String code;
    private String stateName;

    // other attributes of interest

    // setter & getter methods as needed...
}

@Entity
public class CountryCode {
    // primary key
    @Id // and other annotations, see JPA Spec or tutorials
    private long id;

    private String code;
    private String countryName;

    // other attributes of interest

    // setter & getter methods as needed...
}

要减少CnP代码(与主键处理的通用方面(@Id一样),您可以check this answer。它通过引入{{1}为您提供有关如何更有效地处理此类案例的详细提示通过AbstractEntity注释。

希望有所帮助