Home Answers Viewqa Hibernate Hibernate Mapping Many-to-Many Example

 
 


ratna rathor
Hibernate Mapping Many-to-Many Example
3 Answer(s)      11 months ago
Posted in : Hibernate

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 Pages:
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
Hibernate 4 Many to Many Mapping using Annotation
In this section, you will learn how to do Many to Many Mapping using Annotation
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 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 mapping - Hibernate
hibernate mapping  when will we use one to one, one to many, many to many mapping... give a practical example
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     ... 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 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 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
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 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 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 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 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 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
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 Mapping
In this tutorial we will discuss Hibernate mapping
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 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
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
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
Understanding Hibernate O/R Mapping
Understanding Hibernate O/R Mapping   ...;!DOCTYPE hibernate-mapping PUBLIC  "-//Hibernate/Hibernate Mapping DTD 3.0...; </hibernate-mapping>   Hibernate mapping
Hibernate date mapping
In this section, you will learn about date mapping in Hibernate
Mapping Technics - Hibernate
Mapping Technics  Hai i want some clarifications about one-to-many bidirectional relationship
on collection mapping - Hibernate
. The index informs hibernate whether a particular in-memory object is the same one
Hibernate mapping annotations
In this section, you will learn about the annotations used for various mapping in Hibernate
Hibernate - Hibernate
one example   Hi mamatha, Hibernate 3.0, the latest Open Source... from Hibernet.org.Hibernate is a solution for object relational mapping... not understandable for anybody learning Hibernate. Hibernate provides a solution to map
Hibernate One to Many Indexed Mapping
In this section, you will learn to one to many indexed mapping in Hibernate to preserve mapping order
Complete Hibernate 4.0 Tutorial
Hibernate One to Many XML Mapping <list> Example Hibernate... XML mapping <array> Example Hibernate Many... Example With Eclipse Hibernate O/R Mapping Hibernate Supported Databases List
Hibernate - Hibernate
Hibernate SessionFactory  Can anyone please give me an example...;1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate
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 Tutorials
framework. Hibernate takes care of the mapping from Java classes to database tables... to run the example in the Eclipse.   Understanding Hibernate O/R Mapping This section describes the each component of the hibernate mapping
Hibernate One to One Bi-directional Mapping
In this section, you will learn one to one bi-directional mapping in Hibernate
Hibernate One to One Mapping using XML
In this section, you will learn One to One mapping of table in Hibernate using Xml
Hibernate:What is hibernate?
| Hibernate | Database Server Hibernate provide a way of mapping... of interacting with the database overcomes. Click here for hibernate example.  ... | Database Server Hibernate provide a way of mapping of applications class
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
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
Hibernate criteria example using struts2
Hibernate criteria example using struts2 This hibernate criteria example using struts2 is used for defining the basics of criteria. The hibernate criteria... create query without HQL. In this hibernate criteria example using struts2, we
Hibernate Example
This tutorial illustrate an example of hibernate
org.hibernate.InvalidMappingException: Could not parse mapping document - Hibernate
org.hibernate.InvalidMappingException: Could not parse mapping document .... Exception occur:Could not parse mapping document from resource event/Sample.hbm.xml org.hibernate.InvalidMappingException: Could not parse mapping
What is hibernate ?
What is hibernate ?   What is hibernate ? explain with simple example.   Hibernate is an Open Source persistence technology. It provides... Hibernate provide a way of mapping of applications class to the database table
Hibernate Annotations Example
Hibernate Annotations Example In this section we will see how we can develop Hibernate Annotations based example program. After completing this tutorial you... an example of Entity class with Hibernate Annotations @Entity @Table(name

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.