Software Development

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.

[wp_ad_camp_1]

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.

[wp_ad_camp_2]

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

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

[wp_ad_camp_4]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like