Tech I Enjoy Logo

Custom Search




  Home >> Hibernate

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.


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=?
This means I have managed to create a one to many mapping persisted in database tables.
If you like to share your comment/suggestions/feedback relating to this Page, you can do so by droping us an email at usingframeworks @ gmail . com with the subject line mentioning URL for this Page (i.e, /Hibernate-One-to-Many-mapping-example.php) or use this LINK. As per this website's privacy policy, we never disclose your email id, though we shall post your comments/suggestions/feedback with your name (optional) and date on this Page. If you don't want your comments/suggestions/feedback to be shared in this Page, please mention so in your email to us. Thank you very much..... If anything missed out , please let me know at techienjoy at yahoo . com
Class Hierarchy Mapping Example :
class hierarchy mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate Bag Mapping Example :
class mapping using Bag Tag example using Hibernate
Framework and a simple to follow steps.
Hibernate Property Formula :
Hibernate Example on Property
Tag with ease to do code walk-through
Hibernate Transaction on JBoss :
Explaining Transaction using Hibernate
on JBoss Application Server.
Hibernate Example on Filter :
Example on using Filter using Hibernate Framework
to work with.
Hibernate Join Example :
Using Table join explained with an example
while using Hibernate Framework.
Hibernate one to one mapping Example :
one to one mapping explained using an example
and Hibernate Framework.
Hibernate Interceptor Example :
Example on using Interceptor using Hibernate Framework
with source code explained.
Hibernate class heirarchy mapping :
Hibernate Example on mapping
class hierarchy using various ways
of persisting into database
tables.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Example on composite Primary key :
Example on using Hibernate Framework
to work with mapping using composite
Primary key.
Hibernate Example on Filter Criteria :
Example on using Filter Criteria
using Hibernate Framework to work with.
Hibernate Named Query Example :
Named Query markup using an example
and Hibernate Framework.
Hibernate Many to Many Mapping Example :
Many to many mapping example using Hibernate
Framework and a simple to follow steps.
List of Examples on Hibernate :
List of example using Hibernate.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Interview Questions :
Interview Questions on Hibernate with answer.
Example on persisting Class Hierarchy :
Example on using Hibernate Framework
to persist Class Hierarchy into database.
Hibernate Insert Update control :
Hibernate Example on controlling
insert and update attributes
Hibernate Component Property :
Hibernate Example on Component 
with source code explained.


References :
Tags: Hibernate Class Hierarchy Persist example
Tags: Hibernate composite primary key
Tags: Hibernate criteria filter example
Tags: Hibernate Filter Example
Tags: Hibernate Interceptor example
Tags: Hibernate Interview Questions
Tags: Hibernate join example
Tags: Hibernate Many to Many Mapping Example
Tags: Hibernate mapping bag
Tags: Hibernate mapping class hierarchy table per subclass
Tags: Hibernate named query markup
Tags: Hibernate One to Many mapping example
Tags: Hibernate One To One Mapping Example
Tags: Hibernate scenario one to many
Tags: Hibernate transaction jboss
Tags: Hibernate



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions