A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. We already have seen how to map Set collection in hibernate, so if you already learned Set mapping then you are all set to go with one-to-many mapping.
A Set is mapped with a <set> element in the mapping table and initialized with java.util.HashSet. You can use Set collection in your class when there is no duplicate element required in the collection.
Consider a situation where we need to store our employee records in EMPLOYEE table which will have following structure:
There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects:
Let us implement our POJO class Employee which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in Set variable.
Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical.
Let us develop our mapping file which instructs Hibernate how to map the defined classes to the database tables.
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 certificates 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 CERTIFICATE tables.
If you check your EMPLOYEE and CERTIFICATE 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.