Advertisement
Home > Hibernate Tutorial > One to Many mapping example > CodePlease log in to add or reply to any matter<- requires login or
RMI Example

Home > Hibernate Tutorial > One to Many mapping example > Code
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
ways create Hibernate SessionFactory
Description : Example
More...


Written By : Amit
Title :
Spring Hibernate Integration example
Description : Example
More...


Written By : Amit
Title :
ORM Hibernate Best FIT
Description : Discussion
More...


Written By : Amit
Title :
One to Many mapping example
Description : Code
More...


Written By : Amit
Title :
Many to Many Mapping Example
Description : code
More...


Written By : Amit
Title :
Interview questions answer
Description : discussion
More...


Written By : Amit
Title :
Interceptor use log SQL statements
Description : example code
More...


Written By : Amit
Title :
Class Hierarchy Persist example
Description : code
More...

one to many Hibernate, Mapping, one, Many, Hibernate, Tutorial, Article
Author : Amit
Date (Year/Month/Date): 2009-02-18 One to Many mapping and writing HBM file
Hibernate mapping explained:

One-to-Many type of mapping
example:

Case study: A Department can
have many employees and an
Employee can be assigned to
one Department.

So Employee and Department are
having one to many type of
mapping, is explained here with
a one-to-many type of mapping
in Hibernate.
So Department and Employees can share a one-to-many type of mapping.

Advertisement
My Software environment for this example: 1. Eclipse 3.2 2. JDK 1.5 3. Hibernate 3.2 Hibernate one to many mapping can be realized by using specific tags like <one-to-many>, but I am using it along with <set> tag. In this example, POJO (Plain Old Java Object) are Dept and Employee.
/** * This source is provided as is, without any warranty * and /or guaranty of any kind. * Copyright (C) 2008, iSHTIAK, All Rights Reserved. * You can use it for Personal Learning purpose only. * E-mail: usingframeworks@gmail.com */ Dept.java package demo; import java.util.Set; public class Dept { private int deptId; private String deptName; private Set employees; public int getDeptId() { return deptId; } public void setDeptId(int deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public Set getEmployees() { return employees; } public void setEmployees(Set employees) { this.employees = employees; } }
Dept is a simple POJO class with a employees field declared as Set for storing all employees in it.
/** * This source is provided as is, without any warranty * and /or guaranty of any kind. * Copyright (C) 2008, iSHTIAK, All Rights Reserved. * You can use it for Personal Learning purpose only. * E-mail: usingframeworks@gmail.com */ Employee.java package demo; public class Employee { private int employeeId; private String employeeName; private Dept dept; public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } }
HBM mapping file is as mentioned below: In order to create this mapping, first of all I placed normal <class> tag for Dept and Employee, with a id for the primary key and property tags for each fields within Dept and Employee. In order to use <one-to-many> tag , one should have a collection of many items at one side, and we can see employees field in Dept. So there has to have a collection tag like <set> tag inside <class> tag for Dept.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="demo"> <class name="Dept" table="dept"> <id name="deptId" column="dept_id"> <generator class="assigned"/> </id> <property name="deptName" column="dept_name" type="java.lang.String"/> <set name="employees" table="employee" cascade="persist,delete"> <key column="dept_id" /> <one-to-many class="Employee"/> </set> </class> <class name="Employee" table="employee"> <id name="employeeId" column="employee_id"> <generator class="assigned"/> </id> <property name="employeeName" column="employee_name" type="java.lang.String"/> <one-to-one name="dept" class="Dept" /> </class> </hibernate-mapping>
Corresponding tables in database (for this example, I have used HSQLDB), following are the SQL (for HSQLDB as database):
create table dept (dept_id integer, dept_name varchar(20), primary key (dept_id)) create table employee (employee_id integer, employee_name varchar(50), dept_id integer, primary key (employee_id), foreign key(dept_id) references dept(dept_id));
hibernate.cfg.xml file that contains all the configuration settings for this example is as shown below:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- properties --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost/</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <property name="show_sql">true</property> <property name="current_session_context_class">thread</property> <!-- mapping files --> <mapping resource="demo/DeptsEmployee.hbm.xml"/> </session-factory> </hibernate-configuration>
Client code for testing this example could be something like as follows: If wanted to have complete source code of this Client program, then Please REFER THIS
if(sessionFactory != null) { Session session = sessionFactory.getCurrentSession(); Transaction trans = session.getTransaction(); trans.begin(); Employee emp1 = new Employee(); emp1.setEmployeeId(1001); emp1.setEmployeeName("test1"); Employee emp2 = new Employee(); emp2.setEmployeeId(1002); emp2.setEmployeeName("test2"); Employee emp3 = new Employee(); emp3.setEmployeeId(1003); emp3.setEmployeeName("test3"); Set emps = new HashSet(); emps.add(emp1); emps.add(emp2); emps.add(emp3); Dept dept = new Dept(); dept.setDeptId(1001); dept.setDeptName("test dept1"); dept.setEmployees(emps); session.persist(dept); trans.commit(); }
Here in this client, I am just creating three employees and then creating a dept and associating these already created employees to dept. This way, I am getting a following console as output:
Hibernate: insert into dept (dept_name, dept_id) values (?, ?) Hibernate: insert into employee (employee_name, employee_id) values (?, ?) Hibernate: insert into employee (employee_name, employee_id) values (?, ?) Hibernate: insert into employee (employee_name, employee_id) values (?, ?) Hibernate: update employee set dept_id=? where employee_id=? Hibernate: update employee set dept_id=? where employee_id=? Hibernate: update employee set dept_id=? where employee_id=?
Advertisement
This means I have managed to create a one to many mapping persisted in database tables.
Author of this article/writeup has expressed his/her willingness
to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).

Commented By ->
Girish
Can you please explain me with example on how to run/change 
this example if dept and employee tables are having composite
primary key?

How one-to-many mapping to be done in case of composite 
primary keys for dept such as 
id  of type integer, dept_name of type Varchar2(200) and dept_location as
varchar2(10) etc. and the foreign key for these three primary keys
are from three different tables?

I am not sure whether this is feasible.
Please help. Thanks in advance.


Commented By ->
Amit
Please refer to this complete source of client for those who
are starting to learn Hibernate and don't want to refer
some where else to write this test client program.

This client can be written by many other ways as well.

/**
*  This source is provided as is, without any warranty
*  and /or guaranty of any kind.
*  Copyright (C) 2008, ISHTIAK, All Rights Reserved.
*  You can use it for Personal Learning purpose only.
*  E-mail: usingframeworks@gmail.com
*/

package demo;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Client {
	// Hibernate SessionFactory
    SessionFactory sessionFactory;
    public Client() {
    //Hibernate Configuration
      Configuration conf = new Configuration();
      //Loading configuration properties file and building Hibernate
SessionFactory.
      sessionFactory = conf.configure("hibernate.cfg.xml").buildSessionFactory();
      if(sessionFactory != null) {
        Session session = sessionFactory.getCurrentSession();
        Transaction trans = session.getTransaction();
        trans.begin();
        Employee emp1 = new Employee();
        emp1.setEmployeeId(1001);
        emp1.setEmployeeName("test1");
        Employee emp2 = new Employee();
        emp2.setEmployeeId(1002);
        emp2.setEmployeeName("test2");
        Employee emp3 = new Employee();
        emp3.setEmployeeId(1003);
        emp3.setEmployeeName("test3");

        Set emps = new HashSet();
        emps.add(emp1);
        emps.add(emp2);
        emps.add(emp3);
        Dept dept = new Dept();
        dept.setDeptId(1001);
        dept.setDeptName("test dept1");
        dept.setEmployees(emps);
        session.persist(dept);
        trans.commit();
      }
     
    }
    /**
     * Client main method
     * @param args
     */
    public static void main(String[] args) {
       new Client(); 
    }
}

Hibernate SessionFactory can be created by using SpringFramework
by using inject mechanism, thus avoiding code related to 
creation of Hibernate SessionFactory in the client program.

Commented By ->
Guddu
In this example, Client program has the Dept object with a collection of 
Employee object and then it is persisted in database.
In this scenario if <set> tag doesn't have the cascade="persist,delete"
as attribute, then we may have to first save or persist all the
Employee objects and then proceed with persisting Dept object.
Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
3,19
Enter bigger number from above :*
Home > Hibernate Tutorial > One to Many mapping example > Code
Visitor/User submitted related resources:
(Visible upon review and approved by this site Administrator)
Referred By Name *:
Resource URL *: (e.g, URL should be starting with http://www.-----.---)
 
Resource Short Description *:
26,18
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
This List is generated as on 2009-07-12 (YYYY-MM-DD)
#Discuss-these : questions-and-answer : Interview-Questions-on-Java
#Question-on-Session-Factory-Creation : SessionFactory : Hibernate-Tutorial
#On-Hibernate : Interview-Questions : Hibernate-Tutorial
#Example : mapping-class-hierarchy-table-per-subclass : Hibernate-Tutorial
#Example : ways-create-Hibernate-SessionFactory : Hibernate-Tutorial
#Example : Spring-Hibernate-Integration-example : Hibernate-Tutorial
#Discussion : ORM-Hibernate-Best-FIT : Hibernate-Tutorial
#Code : One-to-Many-mapping-example : Hibernate-Tutorial
#code : Many-to-Many-Mapping-Example : Hibernate-Tutorial
#discussion : Interview-questions-answer : Hibernate-Tutorial
#example-code : Interceptor-use-log-SQL-statements : Hibernate-Tutorial
#code : Class-Hierarchy-Persist-example : Hibernate-Tutorial
#discussion : Case-study-Hibernate : Hibernate-Tutorial
#With-Answer : Hibernate-Interview-Questions : Hibernate-Tutorial
#Discussed : Hibernate-Interview-questions-answer : Hibernate-Tutorial
#Question : Hibernate-Transaction : Hibernate-Tutorial
#Example-Case-study : Contextual-Session : Hibernate-Tutorial
#Design-with-example-code : Struts2-Hibernate : Hibernate-Tutorial
#Hibernate-query : Hibernate-Criteria : Hibernate-Tutorial
#Hibernate-Criteria-Example : Hibernate-Filter-Example : Hibernate-Tutorial
#Hibernate-Filter-Example : Hibernate-Filter : Hibernate-Tutorial
#Hibernate-Sample : Hibernate-many-to-one : Hibernate-Tutorial
#Hibernate-Sample-Example : Hibernate-named-query : Hibernate-Tutorial
#Composite-Primary-Key : Hibernate-Composite-Key : Hibernate-Tutorial
#Mapping-Example : Hibernate-one-to-one : Hibernate-Tutorial
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed matterials, content of these pages may 
become out of date over a period of time. Therefore all visitor/users of this web 
site are requested/advised to refer to the originating parties/sources for the 
latest changes and happenings for detailed information. This information is not 
intended to be a substitute for the original reference provided by the originating 
parties/sources.