Hibernate – Component Mapping
In general, a student can have an address/employee can have an address. For these kind of requirements, we can follow Component mapping. It is nothing but a class having a reference to another class as a member variable. i.e. inside the ‘student’ class, we can have the ‘address’ class as a member variable. In MySQL, only a single table is enough which holds the information of all the attributes of both classes. Here in our example, we can see ‘student’ as primary class and it has ‘address’ as member variable.
MySQL table structure for Student:
-- Student table create table Student( studentId INT NOT NULL auto_increment, firstName VARCHAR(20) default NULL, lastName VARCHAR(20) default NULL, grade INT default NULL, streetName VARCHAR(40) default NULL, -- Belongs to Address class cityName VARCHAR(40) default NULL, -- Belongs to Address class stateName VARCHAR(40) default NULL, -- Belongs to Address class zipCode VARCHAR(10) default NULL, -- Belongs to Address class PRIMARY KEY (studentId) );
It is enough if we have only 1 table and it should have all the fields specified in the second class. Here our first class is ‘Student’ and second class is ‘Address’. Let us see the POJO classes
This project is a maven driven project. Hence let us start with pom.xml
For hibernate, hibernate.cfg.xml is the main configuration file
Our mapping resource is student.hbm.xml.
Now let us see the main class where we can do a normal CRUD operation. Let us see the steps of addition and updation of a student in this example.
On running the project, we can see the below output.
MySQL output also matches the same
By using component mapping, the association of class elements can be done easily and in MySQL, it is enough if we have a single table only to satisfy the component mapping.
Please Login to comment...