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









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 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 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 using Annotation
hibernate mapping - Hibernate
hibernate mapping  when will we use one to one, one to many, many to many mapping... give a practical example
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... the example and see the data into database.   Hibernate one-to-many...'s try many-to-many example.   Hibernate many-to-one
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
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 Mapping
In this tutorial we will discuss Hibernate mapping
Hibernate Mapping
O/R mapping tool.   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
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
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 Mapping
In this section, you will learn about Hibernate Mapping
What is component mapping in Hibernate?
What is component mapping in Hibernate?  Hi, What is component mapping in Hibernate? thanks
view mapping - Hibernate
view mapping  How can we do mapping in hibernate
Hibernate XML Mapping
In this section, you will learn how to do XML mapping in Hibernate
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
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
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
Mapping Technics - Hibernate
Mapping Technics  Hai i want some clarifications about one-to-many bidirectional relationship
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...="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd
Hibernate Collection Mapping
("**********Hibernate Collection Mapping Example using Xml************"... as follows : Hibernate Collection Mapping Example Using XML **********Hibernate Collection Mapping Example using Xml************ Hibernate: select employee
on collection mapping - Hibernate
. The index informs hibernate whether a particular in-memory object is the same one
How to write create JPA Many-to-Many Relationship in Java?
How to write create JPA Many-to-Many Relationship in Java?  In an project there is requirement to make the many to many relationship between the tables. how to achieve the many to many relationship in JPA project? Thanks  
Hibernate Mapping Files
Hibernate Mapping Files       Hibernate Mapping Files: In this section I will describe you the necessary Hibernate Mapping Files that is required
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
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 Example
This tutorial illustrate an example of hibernate
What is the root level element in a hibernate mapping file?
What is the root level element in a hibernate mapping file?  Hi, What is the root level element in a hibernate mapping file? This question was asked in Hibernate mapping file. Thanks   Hi, The root element
Hibernate 4 One to Many mapping using XML
In this section, you will learn how to do one to many mapping of tables in Hibernate using Xml
Hibernate One to One Mapping using XML
In this section, you will learn One to One mapping of table in Hibernate using Xml
Hibernate One to One Bi-directional Mapping
In this section, you will learn one to one bi-directional mapping in Hibernate
Hibernate 4 One to One Mapping using Annotation
Hibernate One to One Mapping using Annotation
Hibernate 4 One to One Mapping using Annotation
Hibernate One to One Mapping using Annotation
Give a one to one example in Hibernate.
Give a one to one example in Hibernate.  Hello, Can you give me one to one example in Hibernate..Thanks....   Hello, TO read about One...: Hibernate One-to-one Relationships Hibernate One to One Bi-directional Mapping
Understanding Hibernate O/R Mapping
Understanding Hibernate O/R Mapping   ...; <!DOCTYPE hibernate-mapping PUBLIC  "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0
Diff Bn Uni and Bi-directional Mapping in Hibernate - Hibernate Interview Questions
and bidirectional mapping in hibernate.  Hi I am sending links where u can find lots of hibernate examples, that will solve your problem. http...Diff Bn Uni and Bi-directional Mapping in Hibernate   Hi Friends
What is Hibernate one to one relation?Any example..
Relationships Hibernate Relationships mapping example Hibernate 4 One to One Mapping...What is Hibernate one to one relation?Any example..  Hello, What is Hibernate one to one relation? Is there any example of it.. Thanks..  
Dirty Checking In Hibernate Example
Dirty Checking In Hibernate Example  What is the example of Dirty Checking in Hibernate? Give me some of the example code? Thanks
Hibernate Criteria And Or Example
Hibernate Criteria And Or Example  Hibernate Criteria And Or Example I want example of Hibernate Criteria And Or in Java Thanks   Example of Hibernate Criteria And Or Criteria Check the tutorial Hibernate Criteria
Hibernate 4 One to Many mapping using Annotation
In this section, you will learn how to do one to many mapping in Hibernate using Annotation

Ads