Hibernate

Many to Many Mapping
Previous Home Next

Many to many mapping tells us how to implemented using a Set java collection that does not contain any duplicate element and how to map Set collection in hibernate.In the many to many relationship we can create relation we use many table.

For the many to many mapping we use the to mapped a set of element which initilized in java by the java.util.HashSet method. When we need the duplicated element then we use the Set collection in our class.

In the many to many mapping relation we need to create 3 table in the database. For this we have given some basic step those step are as below:

Step 1. Create a Seperate Database


create database hibernate_pro;

Step 2. Now Use this database (after doing this all table should be created with in the database)


use database;

Step 3. Create a table inside the database


create table STUDENT1
(
STUDENT_ID INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL, 
STUDENT_NAME VARCHAR(40)
);

Step 4. Create a another table for Mapping


create table STUDENT_COURSE
(
STUDENT_ID INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL,
COURSE_ID INT(4)
);

Step 5. Create a another table


CREATE TABLE COURSE
(
COURSE_ID INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL, 
COURSE_NAME);

Step 6. Now we need to create a configuration file which help us to making the connection between application and database. Name should be the file of the configuration file hibernate.cfg.xml file.


<?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 we need to create the mapping file for the mapping with the database.

Course.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 4 Nov, 2014 5:30:48 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="mypack.Course" table="COURSE" catalog="hibernate_pro" optimistic-lock="version">
        <id name="courseId" type="java.lang.Integer">
            <column name="COURSE_ID" />
            <generator class="identity" />
        </id>
        <property name="courseName" type="string">
            <column name="COURSE_NAME" length="40" />
        </property>
    </class>
</hibernate-mapping>

Student1.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 4 Nov, 2014 5:30:48 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="mypack.Student1" table="STUDENT1" 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>

StudentCourse.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 4 Nov, 2014 5:30:48 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="mypack.StudentCourse" table="STUDENT_COURSE" catalog="hibernate_pro" optimistic-lock="version">
        <id name="studentId" type="java.lang.Integer">
            <column name="STUDENT_ID" />
            <generator class="identity" />
        </id>
        <property name="courseId" type="java.lang.Integer">
            <column name="COURSE_ID" />
        </property>
    </class>
</hibernate-mapping>

Step 8. Now we create the POJO class. In the pojo class we create the getter methods and setter method for setting and getting data from the database and in the database.

Courese.java


 package mypack;
// Generated 4 Nov, 2014 5:30:47 AM by Hibernate Tools 4.3.1
/**
 * Course generated by hbm2java
 */
public class Course  implements java.io.Serializable {
     private Integer courseId;
     private String courseName;

    public Course() {
    }

    public Course(String courseName) {
       this.courseName = courseName;
    }
   
    public Integer getCourseId() {
        return this.courseId;
    }
    
    public void setCourseId(Integer courseId) {
        this.courseId = courseId;
    }
    public String getCourseName() {
        return this.courseName;
    }
    
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

}

 

Student1.java


package mypack;
// Generated 4 Nov, 2014 5:30:47 AM by Hibernate Tools 4.3.1
/**
 * Student1 generated by hbm2java
 */
public class Student1  implements java.io.Serializable {
     private Integer studentId;
     private String studentName;

    public Student1() {
    }

    public Student1(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;
    }
}

StudentCourse.java


package mypack;
// Generated 4 Nov, 2014 5:30:47 AM by Hibernate Tools 4.3.1
/**
 * StudentCourse generated by hbm2java
 */
public class StudentCourse  implements java.io.Serializable {
     private Integer studentId;
     private Integer courseId;

    public StudentCourse() {
    }

    public StudentCourse(Integer courseId) {
       this.courseId = courseId;
    }
   
    public Integer getStudentId() {
        return this.studentId;
    }
    
    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }
    public Integer getCourseId() {
        return this.courseId;
    }
    
    public void setCourseId(Integer courseId) {
        this.courseId = courseId;
    }
}

Step 9. Now we create Main() method class to access to all mapping file and for inserting the data into the database.


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;
public class MainClass 
{
    public static void main(String aa[])
    {
        Session ses = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try
        {
            tx = ses.beginTransaction();
            Set <Course> course = new HashSet<Course>();
            course.add(new Course("Maths"));
            course.add(new Course("HomeScience"));
            Student1 st1 = new Student1("ram", course);
            Student1 st2 = new Student1("gopal", course);
            Session.save(Student1);
            Session.save(Student2);
            Transaction.commit();
            
        }catch(HibernateException e)
        {
            Transaction.rollback();
            e.printStackTrace();
        }finally
        {
            ses.close();
        }
    }
}

Save it by MainClass.java and attach all required jar file in the application. and compile each java file and run by MainClass.java

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: