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]
Address.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
publicclassAddress{
....
privateStringcity;
publicStringgetCity(){
returncity;
}
publicvoidsetCity(Stringcity){
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.
@Embeddable Address class
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
importjavax.persistence.Embeddable;
@Embeddable
publicclassAddress{
....
privateStringcity;
publicStringgetCity(){
returncity;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
....
}
Then in @Entity classes, used as reference type for instance variables annotated with @Embedded.
[wp_ad_camp_2]
Employee.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
importjavax.persistence.Entity;
@Entity
publicclassEmployee{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
privateintidEmployee;
...
@Embedded
privateAddress 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.