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.

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

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.

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 is given below :

The jar file used in the example 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>

<mapping class="net.roseindia.Student" />
<mapping class="net.roseindia.Course" />

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

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

package net.roseindia;

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.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student {
@Id
@Column(name="student_id")
@GeneratedValue
private Long studentId;

@Column(name="student_name")
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;
}

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="student_course",[email protected](name="student_id")},[email protected](name="course_id")})
private Set<Course> courses = new HashSet<Course>();

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

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

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

package net.roseindia;

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

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 = "course")
public class Course {
@Id
@Column(name = "course_id")
@GeneratedValue
private Long courseId;

@Column(name = "course_name")
private String courseName;

@ManyToMany(mappedBy="courses")
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;
}
}

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;

@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
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 Annotation ");

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

Course c1=new Course("Cryptography");
Course c2=new Course("Java");

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

After execution, you will get the following output in console :

Hibernate Many to Many Mapping Example Using Annotation 
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 (?, ?)

In the student table, you should get the following record :

In the course table, you should get the following record :

In the student_course table, you should get the following record :

Download Source Code

Advertisements

Ads
Share on Google+Share on Google+

Hibernate 4 Many to Many Mapping using Annotation

Posted on: February 23, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate 4 Many to Many Mapping using Annotation  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads