SQL Zone is brought to you in partnership with:

Meyyappan has posted 101 posts at DZone. View Full User Profile

Hibernate One-To-Many Mapping Tutorial

06.14.2012
| 99452 views |
  • submit to reddit

In this example you will learn how to map one-to-many relationship using Hibernate. Consider the following relationship between Student and Phone entity.

According to the relationship a student can have any number of phone numbers.

To create this relationship you need to have a STUDENT, PHONE and STUDENT_PHONE table. The relational model is shown below.

To create the STUDENT and PHONE table you need to create the following hibernate mapping files.

Student.hbm.xml is used to create the STUDENT and STUDENT_PHONE table.

<?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>
    <class name="com.vaannila.student.Student" table="STUDENT">
        <meta attribute="class-description">This class contains student details.</meta>
        <id name="studentId" type="long" column="STUDENT_ID">
            <generator class="native" />
        </id>
        <property name="studentName" type="string" not-null="true" length="100" column="STUDENT_NAME" />
        <set name="studentPhoneNumbers" table="STUDENT_PHONE" cascade="all">
			<key column="STUDENT_ID" />
			<many-to-many column="PHONE_ID" unique="true" class="com.vaannila.student.Phone" />
		</set>
    </class>
</hibernate-mapping>

We use many-to-many element to create the one-to-many relationship between the Student and Phone entities. Since a student can have any number of phone numbers we use a collection to hold the values. In this case we use Set. Many-to-many element is usually used to create many-to-many relationship, here we place the unique constraint on the PHONE_ID column, this makes the relationship one-to-many.

Phone.hbm.xml is used to create the PHONE table.

<?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>
	<class name="com.vaannila.student.Phone" table="PHONE">
		<meta attribute="class-description">This class contains student's phone number
			details.</meta>
		<id name="phoneId" type="long" column="PHONE_ID">
			<generator class="native" />
		</id>
		<property name="phoneType" type="string" length="10" column="PHONE_TYPE" />
		<property name="phoneNumber" type="string" length="15" column="PHONE_NUMBER" />
	</class>
</hibernate-mapping>

Now create the hibernate configuration file and add all the mapping files.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver </property>
        <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost </property>
        <property name="hibernate.connection.username">sa</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect </property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create-drop</property>
        <mapping resource="com/vaannila/student/Student.hbm.xml"/>
        <mapping resource="com/vaannila/student/Phone.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

After creating the configuration file, generate java class files using Hibernate Tools.(To generate code using Hibernate Tools refer this example )

The following classes will be generated.

package com.vaannila.student;

// Generated Sep 3, 2009 8:47:06 PM by Hibernate Tools 3.2.4.GA

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

/**
 * This class contains student details.
 */
public class Student implements java.io.Serializable {

	private long studentId;
	private String studentName;
	private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0);

	public Student() {
	}

	public Student(String studentName) {
		this.studentName = studentName;
	}

	public Student(String studentName, Set<Phone> studentPhoneNumbers) {
		this.studentName = studentName;
		this.studentPhoneNumbers = studentPhoneNumbers;
	}

	public long getStudentId() {
		return this.studentId;
	}

	public void setStudentId(long studentId) {
		this.studentId = studentId;
	}

	public String getStudentName() {
		return this.studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public Set<Phone> getStudentPhoneNumbers() {
		return this.studentPhoneNumbers;
	}

	public void setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) {
		this.studentPhoneNumbers = studentPhoneNumbers;
	}

}
package com.vaannila.student;

// Generated Sep 3, 2009 8:47:06 PM by Hibernate Tools 3.2.4.GA

/**
 * This class contains student's phone number
 * 			details.
 */
public class Phone implements java.io.Serializable {

	private long phoneId;
	private String phoneType;
	private String phoneNumber;

	public Phone() {
	}

	public Phone(String phoneType, String phoneNumber) {
		this.phoneType = phoneType;
		this.phoneNumber = phoneNumber;
	}
	
	public long getPhoneId() {
		return this.phoneId;
	}

	public void setPhoneId(long phoneId) {
		this.phoneId = phoneId;
	}

	public String getPhoneType() {
		return this.phoneType;
	}

	public void setPhoneType(String phoneType) {
		this.phoneType = phoneType;
	}

	public String getPhoneNumber() {
		return this.phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}
package com.vaannila.student;

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

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaannila.util.HibernateUtil;

public class Main {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			
			Set<Phone> phoneNumbers = new HashSet<Phone>();
			phoneNumbers.add(new Phone("house","32354353"));
			phoneNumbers.add(new Phone("mobile","9889343423"));
			
			Student student = new Student("Eswar", phoneNumbers);
			session.save(student);
			
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

}

Create the Main class to run the example.

package com.vaannila.student;

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

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaannila.util.HibernateUtil;

public class Main {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			
			Set<Phone> phoneNumbers = new HashSet<Phone>();
			phoneNumbers.add(new Phone("house","32354353"));
			phoneNumbers.add(new Phone("mobile","9889343423"));
			
			Student student = new Student("Eswar", phoneNumbers);
			session.save(student);
			
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

}

On executing the Main class you will see the following output.

The STUDENT table has one record.

The PHONE table has two records.

The STUDENT_PHONE table has two records to link the student and phone numbers.

A single student record points to two phone numbers, this illustrates the one-to-many mapping.

The folder structure of the example is shown below.

You can download the source code of this example here.

Source :Download 

 

Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: