Why do we use @Embeddable In Hibernate

What's the use of @Embedded and @Embeddable In Hibernate ? Because every example i found on internet is inserting data inside of a single table and to do that using two different class. My point is if I am using a single table then I can map all the columns inside of a single class then why should i use different class. and if We use two different table then there is one-to-one and one-to-many hibernate relationship.


Solution 1:

There are two types of objects in Hibernate
1. Value Object
2. Entities

Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone.

Entity Objects are those who can stand alone like College and Student.

So in case of value objects preferred way is to Embed them into an entity object.

To answer why we are creating two different classes: first of all, it's a OOPS concept that you should have loose coupling and high cohesion among classes. That means you should create classes for specialized purpose only. For example, your Student class should only have the info related to Student.

Second point is that by creating different classes you promote re-usability.

When we define the value object for the entity class we use @Embeddable.
When we use value type object in entity class we use @Embedded

Solution 2:

suppose we have employee table annotated with @entity and employee has Address so here i dont want to create two tables i.e employee and address, i just want create only one table i.e employee not Address table then we need to declare Address instance in Employee and add @embedable annotation on top of Address class, so finally we get table employee with its record and address records as well in single employee table