One to Many Mapping in Hibernate by R4R Team

In Hibernate we have a type of mapping pojo class to database with the help of xml file that is one to many mapping.One to many mapping means that one row in a table can be mapped to multiple rows in another table.A many-to-one association is the most common kind of association where an Object can be associated with multiple objects.

Before creating a hibernate application on one to many mapping we need to create a database and tables for One to many mapping.By XML based configuration and then we will implement the same functionality using JPA annotations. So we have here some basic step to create a application with one to many mapping those step are a below:


Step 1. create database hibernate_pro;

Step 2. use hibernate_pro;

Step 3. create table STUDENT

              (

                student_id int(10) primary key auto_increment not null,

                student_name varchar(40)

               )


Step 4. create table STUDENT_PHONE

(

student_id int(10) primary key auto_increment not null,

phone_id int(10)

);

Step 5. create table PHONE

         (

          phone_id int(10) primary key auto_increment not null,

          phone_type varchar(100),

          phone_number int(11)

          );


Step 6. create a hibernate.cfg.xml file for connectivity with database


<?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.dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_pro?zeroDateTimeBehavior=convertToNull</property>

    <property name="hibernate.connection.username">root</property>

    <property name="hibernate.connection.password">root</property>

  </session-factory>

</hibernate-configuration>


Step 7. Now create hibernate mapping file for each table.


(1) for student.hbm.xml


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- Generated 3 Nov, 2014 9:40:15 PM by Hibernate Tools 4.3.1 -->

<hibernate-mapping>

    <class name="mypack.Student" table="STUDENT" catalog="hibernate_pro" optimistic-lock="version">

        <id name="studentId" type="java.lang.Integer">

            <column name="student_id" />

            <generator class="identity" />

        </id>

        <property name="studentName" type="string">

            <column name="student_name" length="40" />

        </property>

    </class>

</hibernate-mapping>


(2) Phone.hbm.xml


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- Generated 3 Nov, 2014 9:40:15 PM by Hibernate Tools 4.3.1 -->

<hibernate-mapping>

    <class name="mypack.Phone" table="PHONE" catalog="hibernate_pro" optimistic-lock="version">

        <id name="phoneId" type="java.lang.Integer">

            <column name="phone_id" />

            <generator class="identity" />

        </id>

        <property name="phoneType" type="string">

            <column name="phone_type" length="100" />

        </property>

        <property name="phoneNumber" type="java.lang.Integer">

            <column name="phone_number" />

        </property>

    </class>

</hibernate-mapping>


(3) StudentPhone.hbm.xml


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- Generated 3 Nov, 2014 9:40:15 PM by Hibernate Tools 4.3.1 -->

<hibernate-mapping>

    <class name="mypack.StudentPhone" table="STUDENT_PHONE" catalog="hibernate_pro" optimistic-lock="version">

        <id name="studentId" type="java.lang.Integer">

            <column name="student_id" />

            <generator class="identity" />

        </id>

        <property name="phoneId" type="java.lang.Integer">

            <column name="phone_id" />

        </property>

    </class>

</hibernate-mapping>


Step 8. create POJO class for inserting the data in the table via mapping file.


(1)StudentPhone.java

package mypack;

// Generated 3 Nov, 2014 9:40:15 PM by Hibernate Tools 4.3.1

/**

 * StudentPhone generated by hbm2java

 */

public class StudentPhone  implements java.io.Serializable {

     private Integer studentId;

     private Integer phoneId;

    public StudentPhone() {

    }

    public StudentPhone(Integer phoneId) {

       this.phoneId = phoneId;

    }

    public Integer getStudentId() {

        return this.studentId;

    }

    public void setStudentId(Integer studentId) {

        this.studentId = studentId;

    }

    public Integer getPhoneId() {

        return this.phoneId;

    }    

    public void setPhoneId(Integer phoneId) {

        this.phoneId = phoneId;

    }

}

(2) Student.java

package mypack;

// Generated 3 Nov, 2014 9:40:15 PM by Hibernate Tools 4.3.1

/**

 * Student generated by hbm2java

 */

public class Student  implements java.io.Serializable {

     private Integer studentId;

     private String studentName;

    public Student() {

    }

    public Student(String studentName) {

       this.studentName = studentName;

    }

    public Integer getStudentId() {

        return this.studentId;

    }

    public void setStudentId(Integer studentId) {

        this.studentId = studentId;

    }

    public String getStudentName() {

        return this.studentName;

    }

    public void setStudentName(String studentName) {

        this.studentName = studentName;

    }

}

(3) Phone.java

package mypack;

// Generated 3 Nov, 2014 9:40:15 PM by Hibernate Tools 4.3.1

/**

 * Phone generated by hbm2java

 */

public class Phone  implements java.io.Serializable {

     private Integer phoneId;

     private String phoneType;

     private Integer phoneNumber;

    public Phone() {

    }

    public Phone(String phoneType, Integer phoneNumber) {

       this.phoneType = phoneType;

       this.phoneNumber = phoneNumber;

    }

    public Integer getPhoneId() {

        return this.phoneId;

    }

    public void setPhoneId(Integer phoneId) {

        this.phoneId = phoneId;

    }

    public String getPhoneType() {

        return this.phoneType;

    }

    public void setPhoneType(String phoneType) {

        this.phoneType = phoneType;

    }

    public Integer getPhoneNumber() {

        return this.phoneNumber;

    }

    public void setPhoneNumber(Integer phoneNumber) {

        this.phoneNumber = phoneNumber;

    }

}


Step 9. Crate main class to run the application.

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package mypack;

import java.util.HashSet;

import java.util.Set;

import net.sf.ehcache.hibernate.HibernateUtil;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Transaction;

/**

 *

 * @author sarvesh

 */

public class DataStore {

    public static void main(String aa[])

    {

        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();

        }

    }

}

After the doing all above save all with his extension and compile all java file and run by main() method class. and then check your database is data inserted in the data base or not?
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!