Hibernate Annotation – @Embedded

@Embeddable annotation is used to avoid mapping and define component in an entity for re-usability.

Let’s say a table Student  have the below fields

Student id

Student name

Address line 1

Address line 2

Address line 3

In database it would be represented with a tupple or single row.

More than one students can also reside at the same address. Example students living in a hostel. For the same to save object heap space, instead of creating one entity we can break it in two entity where in one will get embadedded into another with primary key. We can split it as :

Student Entity

Student id

Student name

Address (reference of object which gets embedded in Db table)

Address Entity

Address line 1

Address line 2

Address line 3

Now, we can resuse the address object in the students as mentioned in below code snippet.

try {

transaction = session.beginTransaction();

Address address = new Address(“Address line 1″, ” Address line 2″, ” Address line 3″);

Student student1 = new Student(“Eswar”, address);

Student student2 = new Student(“Prem”, address);

Student student3 = new Student(“Aseem”, address);

session.save(student1);

session.save(student2);

session.save(student3);

transaction.commit();

} catch (HibernateException e) {

transaction.rollback();

e.printStackTrace();

} finally {

session.close();

}

The @Embedded annotation is used to specify the Address entity should be stored in the STUDENT table as a component.

@Embeddable annotation is used to specify the Address class will be used as a component. The Address class cannot have a primary key of its own, it uses the enclosing class primary key.

It is possible to declare an embedded component inside an entity and even override its column mapping.

2 thoughts on “Hibernate Annotation – @Embedded

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s