Home Hibernate Hibernate4 Hibernate 4 Many to Many Mapping using Xml

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate 4 Many to Many Mapping using Xml

Advertisement
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 Xml

In this section, you will learn how to do many to many mapping of tables in Hibernate using Xml.

In the below example, many to many mapping is done using three mysql table - student, course, student_course. In this example, the concept behind this mapping is - many students may have enroll for many courses and one course can be enrolled by many students.

EXAMPLE

The project hierarchy and jar file used in the project is given below :

The query used to create the database table is given below :

CREATE TABLE `student` ( 
`student_id` bigint(10) NOT NULL auto_increment, 
`student_name` varchar(50) default NULL, 
PRIMARY KEY (`student_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 
CREATE TABLE `course` (                            
  `course_id` bigint(10) NOT NULL auto_increment,  
  `course_name` varchar(50) default NULL,          
  PRIMARY KEY  (`course_id`)                       
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `student_course` ( 
`student_id` bigint(10) NOT NULL, 
`course_id` bigint(10) NOT NULL, 
PRIMARY KEY (`student_id`,`course_id`), 
KEY `FK_course` (`course_id`), 
CONSTRAINT `FK_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`course_id`), 
CONSTRAINT `FK_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1    

CODE

hibernate.cfg.xml ( /src/hibernate.cfg.xml )

<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>

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

Student.java ( /src/net/roseindia/Student.java )

package net.roseindia;

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

public class Student {

private Long studentId;

private String studentName ;

public Student(String studentName) {
this.studentName = studentName;
}

public Student() {
}

public Long getStudentId() {
return studentId;
}

public void setStudentId(Long studentId) {
this.studentId = studentId;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}

private Set<Course> courses = new HashSet<Course>();

public Set<Course> getCourses() {
return courses;
}

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

Student.hbm.xml ( /src/net/roseindia/Student.hbm.xml )

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="net.roseindia">
<class name="Student" table="student">
<id name="studentId" column="student_id">
<generator class="native" />
</id>

<property name="studentName" column="student_name"/>

<set name="courses" table="student_course"
inverse="false" lazy="true" fetch="select" cascade="all">
<key column="student_id" />
<many-to-many column="course_id" class="Course" />
</set>
</class>
</hibernate-mapping>

Course.java ( /src/net/roseindia/Course.java )

package net.roseindia;

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

public class Course {
private Long courseId;

private String courseName;

private Set<Student> students = new HashSet<Student>();

public Course() {
}

public Course(String courseName) {
this.courseName = courseName;
}

public Set<Student> getStudents() {
return students;
}

public void setStudents(Set<Student> students) {
this.students = students;
}

public Long getCourseId() {
return courseId;
}

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

public String getCourseName() {
return courseName;
}

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

Course.hbm.xml( /src/net/roseindia/Course.hbm.xml )

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="net.roseindia">
<class name="Course" table="course">
<id name="courseId" column="course_id">
<generator class="native" />
</id>

<property name="courseName" column="course_name"/>

<set name="students" table="student_course"
inverse="false" lazy="true" fetch="select" cascade="all">
<key column="student_id" />
<many-to-many column="course_id" class="Course" />
</set>
</class>
</hibernate-mapping>

ManageStudent.java( /src/net/roseindia/ManageStudent.java )

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class ManageStudent {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration().addResource("net/roseindia/Student.hbm.xml").addResource("net/roseindia/Course.hbm.xml");
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}


System.out.println("Hibernate Many to Many Mapping Example Using Xml ");

Session session = sf.openSession();
session.beginTransaction();

Course c1=new Course("Operating System");
Course c2=new Course("Cryptography");

Student s1=new Student("Sachin Bharadwaj");
Student s2=new Student("Vikas Sharma");

s1.getCourses().add(c1);
s1.getCourses().add(c2);
s2.getCourses().add(c2);

session.save(s1);
session.save(s2);

session.getTransaction().commit();
session.close();
}
}

OUTPUT

In console, you will get the following message :

Hibernate Many to Many Mapping Example Using Xml 
Hibernate: insert into student (student_name) values (?)
Hibernate: insert into course (course_name) values (?)
Hibernate: insert into course (course_name) values (?)
Hibernate: insert into student (student_name) values (?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)

Data in student table :

Data in course table :

Data in student_course table :

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 23, 2012

Related Tutorials

Discuss: Hibernate 4 Many to Many Mapping using Xml  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Rodrigo
October 4, 2012
Delete is not working properly

Hello I just wanted to know how I can have this many-to-many relation but I need to delete a course and NOT delete the related students. Also delete an student and NOT delete the related courses. For example: student = (id=1). student_course= (id_student=1, id_course=1); (id_student=1, id_course=2); (id_student=1, id_course=3). course (id=1)(id=2)(id=3) Now I delete the student (id=1) student (empty) student_course (empty) course (1) course (2) course (3) With this mapping, hibernet delete all tables! student (empty) student_course (empty) course (empty) Thanks! Rodrigo
DMCA.com