0

JPA – How to use @Embeddable and @Embedded

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

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.

Then in @Entity classes, used as reference type for instance variables annotated with @Embedded.

When an instance of Employee is persisted, the database table content may look something similar to this:

id_employeefirst_namehouse_nocitycountry
1Karl100Makati CityPhilipines
2Pedro101Marikina CityPhilippines

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.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert