Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



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

Have Programming Question? Ask it here!
 
 
 


ratna rathor
Hibernate Mapping Many-to-Many Example
3 Answer(s)      2 years and a month ago
Posted in : Hibernate


How does many to many relationship work in Hibernate?


Advertisement
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... into database.   Hibernate one-to-many relationships example using...; Hibernate many-to-many relationships example using hbm.xml file Now
Hibernate Mapping
In this tutorial we will discuss Hibernate mapping
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
.   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 Mapping
In this section, you will learn about Hibernate Mapping
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
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
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 date mapping
In this section, you will learn about date mapping 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
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 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 mapping annotations
In this section, you will learn about the annotations used for various 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 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 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 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
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
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 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 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
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
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 One to Many Bi-directional Mapping
In this section, you will learn how to do One to Many Bi-Directional Mapping in Hibernate
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
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
Hibernate Example
This tutorial illustrate an example of hibernate
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
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 Mapping
Hibernate One To One Mapping Using Annotation Hi If you are use-to with the Hibernate annotation, then it is very simple to do mapping using hibernate...='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "
Hibernate Mappings
In this section, you will learn how to do mapping in Hibernate
Advertisements
 

 

 

DMCA.com