Hibernate Mapping Many-to-Many Example

Hibernate Mapping Many-to-Many Example

How does many to many relationship work in Hibernate?

View Answers

June 21, 2012 at 6:24 PM

In many to mant relationship each row in table A linked to multiple rows in table B and vice versa.Here is an example of Student and course. one student can chose multiple subject in the same way 1 course can be assigned to multiple student.

Configuration file : hibernate.cfg.xml

<?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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernaterelationship</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>

        <!-- Mapping files -->
        <mapping class="net.roseindia.table.Course" />
        <mapping class="net.roseindia.table.Student" />

    </session-factory>
</hibernate-configuration>

Table classes :

Course.java

package net.roseindia.table;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "course")
public class Course {

    private int courseId;
    private String courseName;

    public Course(String course) {
        // TODO Auto-generated constructor stub
        this.courseName=course;
    }

    @Id
    @GeneratedValue
    @Column(name = "courseId", nullable = false)
    public int getCourseId() {
        return courseId;
    }

    public void setCourseId(int courseId) {
        this.courseId = courseId;
    }

    @Column(name = "courseName", nullable = false)
    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

}

Student.java

package net.roseindia.table;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student {
    private int id;
    private String name;
    private Set<Course> courses = new HashSet<Course>();

    public Student(String name) {
        // TODO Auto-generated constructor stub
        this.name = name;
    }

    public Student(String name, Set<Course> courses) {
        this.name = name;
        this.courses = courses;
    }

    @Id
    @GeneratedValue
    @Column(name = "studentId", nullable = false)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column(name = "studentName", nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToMany(cascade=CascadeType.ALL)
    public Set<Course> getCourses() {
        return courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }



}

June 21, 2012 at 6:24 PM

Continued..

Util Class:HibernateUtil.java

package net.roseindia.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
    private static SessionFactory sessionFactory = null;

    static {
        sessionFactory = new AnnotationConfiguration().configure()
                .buildSessionFactory();
    }

    public static SessionFactory getseSessionFactory() {
        return sessionFactory;
    }
}

Main Class : ManyToMany.java

package net.roseindia.application;

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

import net.roseindia.table.Course;
import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;

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

public class ManyToMany{
    public static void main(String[] args){
        Session session=HibernateUtil.getseSessionFactory().openSession();
        Transaction transaction=null;
        try{
            transaction=session.beginTransaction();
            Set<Course> courses=new HashSet<Course>();
            courses.add(new Course("Maths"));
            courses.add(new Course("Science"));

            Student student1=new Student("Ron", courses);
            Student student2=new Student("Ric",courses);
            session.save(student1);
            session.save(student2);
            transaction.commit();

        }catch(HibernateException he){
            System.out.println(he.getMessage());
        }
        finally{
            session.close();
        }
    }
}

Output:

Hibernate: insert into student (studentName) values (?)
Hibernate: insert into course (courseName) values (?)
Hibernate: insert into course (courseName) values (?)
Hibernate: insert into student (studentName) values (?)
Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?)
Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?)
Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?)
Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?)

September 16, 2012 at 1:41 AM

see this simple annotation example

Ads









Related Tutorials/Questions & Answers:
Hibernate Mapping Many-to-Many Example
Hibernate Mapping Many-to-Many Example  How does many to many relationship work in Hibernate?   In many to mant relationship each row in table A linked to multiple rows in table B and vice versa.Here is an example
Hibernate Many To Many Annotation Mapping
Hibernate Many To Many Annotation Mapping  How to use Many To Many Annotation Mapping in Hibernate?   Hibernate requires metadata like... to another.Hibernate annotation provides annotation-based mapping. Click here
Advertisements
Hibernate 4 Many to Many Mapping using Xml
In this section, you will learn how to do many to many mapping of tables in Hibernate using Xml
Hibernate 4 Many to Many Mapping using Annotation
In this section, you will learn how to do Many to Many Mapping of table in Hibernate using Annotation
Hibernate 4 Many to Many Mapping using Annotation
In this section, you will learn how to do Many to Many Mapping using Annotation
Hibernate Many to Many Self Join using Annotations
In this section, you will learn how to do many to many self join using Annotations in Hibernate
Hibernate Many-to-many Relationships
Hibernate Many-to-many Relationships       Hibernate Many-to-many Relationships - Many to many example in Hibernate. In this example we have used xml
Hibernate Relationships - Hibernate Relationships mapping example
Hibernate Relationships - Hibernate Relationships mapping example... into database.   Hibernate one-to-many relationships example using...; Hibernate many-to-many relationships example using hbm.xml file Now
Many To Many annotation in ejb
Many To Many annotation in ejb   how to define primary key in the third & resulting table obtained from ManyToMany mapping.I tried the mapping but the resulting table is showing only foreign key with the two fields which
Hibernate Mapping
In this tutorial we will discuss Hibernate mapping
Hibernate Mapping
.   Hibernate One-To-One Mapping Example...Hibernate Mapping In this Hibernate Mapping tutorials series you will learn... the complex things easily.  This Hibernate Mapping tutorial is targeted
Jpa many to many relationship
Jpa many to many relationship  I HAVE Employee, EmpSchedule, EmpSubstitution tables Employee EMP_ID NAME PHONE EmpSchedule EMP_ID Start_date End... and EmpSubstituion table is many to many. between these Employee table is association table
Hibernate One to Many XML Mapping list Example
In this section, you will learn how to do one to many mapping using List to retain mapping order in Hibernate
Hibernate One to many XML mapping array Example
In this section, you will learn how to do one to many mapping using array to retain mapping order in Hibernate
Hibernate Mapping
In this section, you will learn about Hibernate Mapping
Explain Hibernate Relationships with example.
Explain Hibernate Relationships with example.  Hello, Please explain various hibernate relationships. And if you can provide some examples that would be a great help.. Thank you....   Hi, Hibernate relational
What is component mapping in Hibernate?
What is component mapping in Hibernate?  Hi, What is component mapping in Hibernate? thanks
JPA Many-to-Many Relationship
JPA Many-to-Many Relationship     ... the many-to-many relationship and how to develop a many-to-many relation in your JPA Application. Many-to-many: In this relationship each record in Table-A may
Hibernate XML Mapping
In this section, you will learn how to do XML mapping in Hibernate
Hibernate One to many XML Mapping bag example
In this section, you will learn how to use element instead of or element in mapping XML file in Hibernate
Hibernate Named Native SQL Query using XML Mapping
In this section, you will learn Named Native SQL Query using XML Mapping in Hibernate with an example
Hibernate date mapping
In this section, you will learn about date mapping in Hibernate
Hibernate one to one mapping using xml
Hibernate one to one mapping using xml  Hi, How to create hibernate... one record in the mapping table. For example employ will have only one current address. Check the example at: Hibernate One-to-one Relationships Thanks
Hibernate mapping annotations
In this section, you will learn about the annotations used for various mapping in Hibernate
Hibernate O/R Mapping
Hibernate O/R Mapping In this tutorial you will learn about the Hibernate O/RM (Object/Relational Mapping). O/RM itself can be defined as a software...;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0
JPA Retrieve Data By Using Many-to-Many Relation
JPA Retrieve Data By Using Many-to-Many Relation...; In the previous section, you had read about the many-to-many relation. Here, you will learn how to retrieve data to database table by using the JPA many-to-many relation
Hibernate Example
This tutorial illustrate an example of hibernate
Hibernate Collection Mapping
;Hibernate Collection Mapping Example Using XML "); Session session... System.out.println("**********Hibernate Collection Mapping Example using Xml... : Hibernate Collection Mapping Example Using XML **********Hibernate Collection
Hibernate association and join example
Example Many to Many XML Example Check more tutorials at Hibernate...Example program of Associations and Joins in Hibernate framework...-to-many etc. We have also provides the appropriate examples of Hibernate
Hibernate One to Many Indexed Mapping
In this section, you will learn to one to many indexed mapping in Hibernate to preserve mapping order
Hibernate Many One One Mapping
Hibernate Mapping And Join Using hibernate we can easily create relationship between two tables. The relationship may be One-To-One, One-To-Many, Many-To-One and Many-To-Many. An Example of One To Many mapping is given below Address

Ads