@Entity and @Embeddable
In Java Persistence API (JPA), a class can either be an @Entity
or a value type. If a class is an @Entity
, it is a persistent class. It represents a database table (or set of tables). If a class is a value type, it is not a persistent class. It may not represent a database table or a set of database tables. It may be used as a reusable component whose properties are used across multiple tables.
Take for instance, an Address class.
[wp_ad_camp_1]
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Address { .... private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } .... } |
A number of tables may have the same fields that collectively represent an address. For example, house no; street; city; zip code; and country.
Reuse Address’ fields in @Entity classes
To be able to reuse the Address
class’ properties (or fields), it has to be annotated with @Embeddable
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import javax.persistence.Embeddable; @Embeddable public class Address { .... private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } .... } |
Then in @Entity
classes, used as reference type for instance variables annotated with @Embedded
.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import javax.persistence.Entity; @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int idEmployee; ... @Embedded private Address homeAddress; ... } |
When an instance of Employee is persisted, the database table content may look something similar to this:
id_employee | first_name | house_no | city | country |
---|---|---|---|---|
1 | Karl | 100 | Makati City | Philipines |
2 | Pedro | 101 | Marikina City | Philippines |
[wp_ad_camp_3]
Two types of Address for @Entity
An Employee may have two addresses – office and home addresses. To achieve that, the @Entity
class may need to use @AttributeOverrides
for each instance variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import javax.persistence.Entity; @Entity public class EmployeeB { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int idEmployee; ... @Embedded @AttributeOverrides( {@AttributeOverride( name="houseNo", column = @Column(name = "homeHouseNo")), @AttributeOverride( name="city", column = @Column(name = "homeCity")), @AttributeOverride( name="country", column = @Column(name = "homeCountry")) }) private Address homeAddress; @Embedded @AttributeOverrides( {@AttributeOverride( name="houseNo", column = @Column(name = "officeBldgNo")), @AttributeOverride( name="city", column = @Column(name = "officeCity")), @AttributeOverride( name="country", column = @Column(name = "officeCountry")) }) private Address officeAddress; ... } |
[wp_ad_camp_4]