我有一个包含以下字段的实体:
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
表中的州代码和CountryCodes
表中的国家/地区代码的3个属性( birthCountryCodeId,citizenshipCountryCodeId 和 addressCountryCodeId )。使用JPA(将Hibernate作为持久性提供程序),如何将上述5个属性(2个州代码和3个国家/地区代码)映射到两个单独的表StateCodes和CountryCodes?
答案 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
注释。
希望有所帮助