Hibernate 4 Many to Many Mapping using Annotation

Ads
 
Tutorials   
What is difference between Hibernate 4 and 5? Hibernate 5.3 features Hibernate 5 JPA Configuration Hibernate 5 persistence.xml example Hibernate 5 JPA Tutorial Hibernate and JPA Example How properties of a class are mapped to the columns of a database table in Hibernate? Hibernate 5 Annotations Maven dependency Hibernate 5 annotationconfiguration Doctype Hibernate-configuration 5 Hibernate 5 Dialect Hibernate 5 configuration dtd Hibernate 5 Hello World Getting started with Hibernate 5 Hibernate 5.2.10 jar Download Hibernate 5.2.10 Maven Dependency Hibernate 5 Maven Dependency Hibernate 5 native query example Hibernate 5 query deprecated When should you use Hibernate? What's new in Hibernate 5? How much time it takes to learn Hibernate? Hibernate envers custom revinfo table Hibernate 5 Envers Hibernate Envers get all revisions Hibernate Examples Hibernate 5 build SessionFactory Example Hibernate 5 SessionFactory Example Hibernate 5 Annotation Example How to download Hibernate 5.x? Hibernate 5 Features Hibernate 5 Tutorials Learning Hibernate ORM - Free Training/Tutorial videos of Hibernate ORM with Java 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 ORM 4.2.21.Final Released - Create CURD application in latest Hibernate Hibernate ORM 4.2.21 Tutorial - Learn Hibernate ORM Framework Hibernate Error: Failed to create sessionFactory object.java.lang.NoClassDefFoundError How to create Hibernate Project in Eclipse?

Hibernate 4 Many to Many Mapping using Annotation

In this section, you will learn how to do 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 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_course` ( 
`student_id` bigint(10) default NULL, 
`course_id` bigint(10) default NULL, 
KEY `FK_course` (`course_id`), 
KEY `FK_student` (`student_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


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

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",joinColumns={@JoinColumn(name="student_id")},inverseJoinColumns={@JoinColumn(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

Ads

Ads