Let us understand Component with the below example:
In our earlier example we have seen the 'Employee' class:
Now, other than the 'id' and 'name' field, the Employee can also have an address. And as we all know the address will contain 'streetName', 'city' and 'pinCode'.
So, the approach we follow in java is, create an 'Address' class with the following attributes:
and refer it in the 'Employee' class:
Now, just think for a moment! The 'Address' class comes to use only when it is referred by the 'Employee' class. In other words the 'Address' class does not have its own identity. Its purpose is only to serve the 'Employee' class. Such kind of objects (i.e. Address) are called as 'VALUE OBJECTS'.
The 'Value Objects'(i.e. the Address) can also be called as a 'Component'.
In the above case all the attributes of the 'Address' class(i.e. streetName, city, pinCode) is used inside the 'Employee' class. And yet we have two different classes in java.
But, what if we don't want two different tables in the database. Instead we want to club all the attributes of 'Address' and 'Employee' class and put it in the 'EMPLOYEE' table itself.
The 'EMPLOYEE' table would look something like the below structure:
ID | NAME | STREET_NAME | CITY | PIN_CODE |
---|---|---|---|---|
To achieve this, 'Component' comes into picture.
Let us follow the below steps for component mapping in Hibernate:
1. Firstly in the mapping file we need to tell Hibernate that the 'Address' class has to be treated as a 'Component'.
The above lines are quite self explanatory.
It means the 'Employee' class has a component called 'Address' and we are informing Hibernate the same using the 'component' tag.
And the 'Address' component has three attributes streetName, city and pinCode. Which we are mapping to the 'EMPLOYEE' table using the 'property' tag.
2. Next, we will be writing the main class where we will be saving the 'Employee' data and its corresponding 'Address' data to the database using Hibernate.
So, what we are doing in the above case is, creating the 'Address' component and assigning values to it.
And since we are referencing 'Address' in the 'Employee' class, we have assigned the 'address' values to the 'Employee' class.
And after saving the data using 'session.save(employee)', we get the data saved to the 'EMPLOYEE' table in the below structure.
ID | NAME | STREET_NAME | CITY | PIN_CODE |
---|---|---|---|---|
1 | John | Walls street | Delhi | 110012 |
And thats all we wanted. It is all because of the statement :
in the mapping file which tells Hibernate that 'Address' class is a component and should be saved in a single row in the 'EMPLOYEE' table.