Advertisement :
   Log In    OR    Register  
  Topics :  
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 : admin
Title :
SessionFactory
Description : Question on Session Factory Creation
More...


Written By : Amit
Title :
Interview Questions
Description : On Hibernate
More...


Written By : Amit
Title :
mapping class hierarchy table per subclass
Description : Example
More...


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


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

Tags/Keywords : 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

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

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).


	
 
Replied By ->
Thangavel
It is well explained, thanks alot for author.
 

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.

Commented By ->
Vamsi
Hi,

This article is really helpful..thanks to the author..

Vamsi

Commented By ->
Afsar
i want total explanation about foreign key

Commented By ->
Amit
Hi Afsar,

I really didn't follow you question.
Can you please elaborate your question a little bit more?

If you are asking more details about foreign key.. then I think you can go through some of the DML
statements and refer some database specific documentation.

Commented By ->
phani
This article was  really helped me a lot....i am very thankful to the authors...could U please provide the
tutorial related to Hibernate and Struts2...
Are you interested in solving a very interesting Technology Stack while Playing this Game          

Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
6,38
Enter bigger number from above :*
Home >>> Hibernate Tutorial >>> One to Many mapping example >>> Code
Visitor/User referred related external URL:
(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 *:
11,3
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER
Terms of Use and Disclaimer :

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed materials, 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.

By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or 
downloading any materials, you agree to and are bound by the terms of use 
described in this page and Usage Terms and Conditions. 
If you do not agree to all of 
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this 
website in any manner. If you are using the website on behalf of your 
employer, you represent that you are authorized to accept these Terms of Use 
on your employer's behalf.

All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any 
of these information, please refer original content/documentation from respective sources. 
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.