A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example a same address object can be associated with multiple employee objects.
Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure:
Further, many employee can have same address, so this association can be presented using many-to-one association. We will store address related information in a separate table which has following structure:
Create both the RBDMS tables and keep them ready for the next implementation.
Let us implement a POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a variable of Address type.
Let us develop our mapping files which instructs Hibernate how to map the defined classes to the database tables. The <many-to-one> element will be used to define the rule to establish a many-to-one relationship between EMPLOYEE and ADDRESS entities.
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail but let us see all the elements of mapping file once again:
Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records alongwith their addresses and then we will apply CRUD operations on those records.
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
You would get following result on the screen, and same time records would be created in EMPLOYEE and ADDRESS tables.
If you check your EMPLOYEE and ADDRESS tables, they should have following records:
Hibernate Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JSP Interview Questions||Java-Springs Interview Questions|
|Java Struts Interview Questions||Log4j Interview Questions|
|Software Development Lifecycle (SDLC) Interview Questions||NHibernate Interview Questions|
|Spring MVC Framework Interview Questions||Apache Struts 2 Interview Questions|
|Spring Aop Interview Questions|
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.