Hibernate Mapping Example

In this example, we will show you how to use hibernate with its mapping capability. We are going to show a one-to-many bi-directional mapping in hibernate using XML mappings. We will configure our hibernate with hibernate.cfg.xml and then we are going to create a mapping with example.hbm.xml . One-to-many relationship is the relationship in which each record in one table is linked to multiple records in another.

1. Introduction

Hibernate is an object-relational mapping(ORM) framework for java language. It provides a way to map Java classes to relational database tables. We can achieve this mapping through XML mapping OR Annotation mapping. In this example, we will be showing this mapping through XML mapping. We will be using one-to-many relationship mapping.

2. Environment

  1. Windows 7
  2. Java version 7
  3. Eclipse Kepler 4.3
  4. Maven 3.0.4
  5. MySQL 5.0.86
  6. JBoss-Hibernate Plugin 4.1.2

3. Example Outline

In this example, we will create a maven project in eclipse with hibernate plugin. We will create two different classes which are related to each other in one-to-many relationships and then create its hibernate XML mapping to generate the mapping between Java objects and database tables. At the end, we will create a test program to test our Java objects for updating and retrieving information from the database.

4. Example

Following are the steps we will perform to create our Hibernate Mapping example in this tutorial.

4.1 Create a Maven Project

Create a new maven project in eclipse. Fill in the details for GroupId as com.javacodegeeks.example and ArtifactId as HibernateMappingExample as shown below

Maven Project
Maven Project

4.2 Add hibernate dependencies

Now we will add the required dependencies for Hibernate. Here we will use Maven’s feature of dependency management in pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.3 Create Hibernate Configuration File

Let’s create a hibernate configuration file hibernate.cfg.xml under resources directory in the project. The hibernate wizard will look like below

Hibernate Configuration XML file
Hibernate Configuration XML file

Do not forget to check “Create a console configuration” checkbox on the screen as shown above. That will be our next step to configure Hibernate Console. The hibernate.cfg.xml file will look like below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

4.4 Hibernate Console Configuration

Once you have selected the checkbox for “Create a console configuration”, click Next to go on the screen shown below for hibernate console and click Finish.

Hibernate Console Configuration
Hibernate Console Configuration

You can open Hibernate Console Configuration view in eclipse and it will show database and all the tables of that database.

4.5 Create Java Objects

Since we are showing one-to-many relationship mapping in this example, we will create two different Java classes. We will create Employee.java and Department.java objects for our example.


package com.javacodegeeks.example;

import java.util.Set;

public class Department {

	private Long id;
	private String departmentName;
	private Set employees;

	public Long getId() {
		return id;

	public void setId(Long id) {
		this.id = id;

	public String getDepartmentName() {
		return departmentName;

	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;

	public Set getEmployees() {
		return employees;

	public void setEmployees(Set employees) {
		this.employees = employees;


package com.javacodegeeks.example

import java.sql.Date;

public class Employee {
        private Long id;

	private String firstname;

	private String lastname;

	private Department department;

	public Employee() {

	public Employee(String firstname, String lastname) {

	public Long getId() {
		return id;

	public void setId(Long id) {
		this.id = id;

	public String getFirstname() {
		return firstname;

	public void setFirstname(String firstname) {
		this.firstname = firstname;

	public String getLastname() {
		return lastname;

	public void setLastname(String lastname) {
		this.lastname = lastname;

	public Department getDepartment() {
		return department;

	public void setDepartment(Department department) {
		this.department = department;

4.6 Map Java Objects to Database

Let’s create a mapping file for each java object to database. In eclipse, under src -> main -> resources, create a file with option Hibernate XML Mapping file (hbm.xml). We will have Employee.hbm.xml and Department.hbm.xml .


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!-- Generated Jul 11, 2016 10:24:48 PM by Hibernate Tools 3.4.0.CR1 -->
    <class name="com.javacodegeeks.example.Employee" table="EMPLOYEE">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="assigned" />
        <property name="firstname" type="java.lang.String">
            <column name="FIRSTNAME" />
        <property name="lastname" type="java.lang.String">
            <column name="LASTNAME" />
        <many-to-one name="department" class="com.javacodegeeks.example.Department" fetch="join">
            <column name="DEPARTMENT_ID" />


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!-- Generated Jul 11, 2016 10:24:48 PM by Hibernate Tools 3.4.0.CR1 -->
    <class name="com.javacodegeeks.example.Department" table="DEPARTMENT">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="assigned" />
        <property name="departmentName" type="java.lang.String">
            <column name="DEPT_NAME" />
        <set name="employees" table="EMPLOYEE" inverse="false" lazy="true">
                <column name="DEPARTMENT_ID" />
            <one-to-many class="com.javacodegeeks.example.Employee"/>

4.7 Create a Hibernate Test Program

Let’s create a test hibernate program to insert some employees for some departments. The source code looks like below


package com.javacodegeeks.example;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateTestMappingProgram {
	private static SessionFactory factory;
	private static ServiceRegistry serviceRegistry;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Configuration config = new Configuration();
		serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
		factory = config.buildSessionFactory(serviceRegistry);
		HibernateTestMappingProgram hbTest = new HibernateTestMappingProgram();


	private long insertEmployee(int id, String firstname, String lastname, String deptName, int deptId)
		Session session = factory.openSession();
		Transaction tx = null;
		Long empIdSaved = null;
		try {
			tx = session.beginTransaction();
		    Department d = new Department();
		    d.setId(new Long(deptId));
			Employee e = new Employee();
			e.setId(new Long(id));
			empIdSaved = (Long) session.save(e);
		} catch(HibernateException ex) {
			if(tx != null)
		} finally {
		return empIdSaved;


5. Conclusion

In this example, we showed how to use hibernate to map one-to-many relationship. We created a test program to test this relationship between Employee and Department.

6. Download

Here we showed how to use Hibernate for mapping relationships in relational database to java objects.

You can download the full source code of this example here: HibernateMappingExample

Yogesh Mali

Yogesh currently lives in Minneapolis and works as a Senior Software Engineer. He has a masters degree in Computer Science from University of Minnesota, Twin Cities. At graduate school, he did research in programming languages because of his love for functional and object oriented programming. Currently he delves into more details of Java, web development and security. Previously he worked as a product manager to create web application for health insurance brokers. In his free time, he listens to music and writes fictional stories.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button