jpa embeddable annotation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, In this article we will learn about jpa embeddable annotation.

JPA embeddable annotation:

This is what javadoc says about jpa embeddable annotation.

Defines a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity.

Consider an example of Person entity which is stored in the database in person table. It is as below.

persontable

The corresponding entity for Person table in JPA will be

You can notice here that the fields area , city and pincode form an address. We can create a separate Address class and tie it to Person . Address class does not need a representation in database. It is simply composed of these three fields. We can encapsulate these to form a new  Address  class and simply have reference of Address from Person . JPA embeddable annotation provides this. You can declare Address class as being embeddable into some other entity. So it class becomes,

To reference this class which is created with jpa embeddable annotation, you can provide @Embedded field in Person class. So it becomes,

Things to notice here,

Persistence unit:

Let us test this out,

This will run successfully and add fields to Person table using the properties of Address class which are embedded in Person entity.

Things to remember:

  • An embedded object specified using jpa embeddable annotation does not represent a table in database
  • It is not an Entity. It is simply owned by some Entity and it forms the field names of owning entity.
  • As Address is not an Entity, the relationship between Person and Address is not termed a a jpa relationship. It is simply an embedded object.
  • The purpose of embedded objects is re-usability. We can re-use address embedded object for some other class which has also the same fields in database representation.

I hope this articled helped understand jpa embeddable annotation.

 

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

4 thoughts on “jpa embeddable annotation

Leave a Reply

Your email address will not be published. Required fields are marked *