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 :