0

I have an entity with the following fields:

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;

As you can see from the above snippet, I have

  • 2 properties (birthStateCodeId, addressStateCodeId) where I use a state code from a StateCodes table, and
  • 3 properties (birthCountryCodeId, citizenshipCountryCodeId, and addressCountryCodeId) where I use a country code from a CountryCodes table.

Using JPA (with Hibernate as persistence provider), how do I map the above 5 properties (2 state codes and 3 country codes) to the two separate tables StateCodes and CountryCodes?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Sunil Kosuri
  • 99
  • 1
  • 15

1 Answers1

2

You could achieve it like this:

@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...
}

Next, define entity classes for both "Code" types as such:

@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...
}

To reduce CnP code (as with the generic aspect of primary key handling (@Id) you can check this answer. It gives you detailed hints on how handle such cases more efficiently by introducing an AbstractEntity via the @MappedSuperClass annotation.

Hope it helps

MWiesner
  • 8,868
  • 11
  • 36
  • 70