Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 8 September 2013

Hibernate Many to Many Mapping (Annotation) Example

In our previous discussion we came across Hibernate One to Many Mapping using Annotation. In this particular blog we will see what is hibernate many to many relationship and how to implement it using Annotations. We will demonstrate the relationship by taking two model classes 'Student' and 'Test' and try to establish a many to many relationship in between them.

Hibernate Many to Many Relationship

Database Setup

-- Dumping database structure for manytomany_db
CREATE DATABASE IF NOT EXISTS `manytomany_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `manytomany_db`;


-- Dumping structure for table manytomany_db.student
CREATE TABLE IF NOT EXISTS `student` (
  `student_id` bigint(10) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(50) DEFAULT NULL,
  `lastname` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Data exporting was unselected.


-- Dumping structure for table manytomany_db.student_test
CREATE TABLE IF NOT EXISTS `student_test` (
  `student_id` bigint(20) NOT NULL,
  `test_id` bigint(20) NOT NULL,
  PRIMARY KEY (`student_id`,`test_id`),
  KEY `FK_MEETING` (`test_id`),
  CONSTRAINT `FK_EMPLOYEE` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`),
  CONSTRAINT `FK_MEETING` FOREIGN KEY (`test_id`) REFERENCES `test` (`test_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Data exporting was unselected.


-- Dumping structure for table manytomany_db.test
CREATE TABLE IF NOT EXISTS `test` (
  `test_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `subject` varchar(50) NOT NULL,
  `max_marks` varchar(50) NOT NULL,
  `marks_obtained` varchar(50) NOT NULL,
  `result` varchar(50) NOT NULL,
  PRIMARY KEY (`test_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Project Structure



Dependencies used in 'Hibernate many to many Mappings'

<?xml version="1.0" encoding="UTF-8"?>
<project>
 <modelVersion>4.0.0</modelVersion>
 <groupId>HibernateCache</groupId>
 <artifactId>HibernateCache</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <description></description>
 <dependencies>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.6</version>
  </dependency>

  <dependency>
   <groupId>javax.transaction</groupId>
   <artifactId>jta</artifactId>
   <version>1.1</version>
  </dependency>

  <dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.12.1.GA</version>
  </dependency>



  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-annotations</artifactId>
   <version>3.5.0-Final</version>
  </dependency>

  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>1.7.5</version>
  </dependency>

  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.7.5</version>
  </dependency>


 </dependencies>
</project>



\src\main\resources\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://localhost:3306/manyToMany_db</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="com.beingjavaguys.domain.Student" />
  <mapping class="com.beingjavaguys.domain.Test" />

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



\src\main\java\com\beingjavaguys\domain\Student.java

package com.beingjavaguys.domain;

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 = "FIRSTNAME")
 private String firstname;

 @Column(name = "LASTNAME")
 private String lastname;

 @Column(name = "EMAIL")
 private String email;

 @Column(name = "PHONE")
 private String phone;

 @ManyToMany(cascade = { CascadeType.ALL })
 @JoinTable(name = "STUDENT_TEST", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "TEST_ID") })
 private Set<Test> test = new HashSet<Test>();

 public Student() {
 }

 public Student(String firstname, String lastname, String email, String phone) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.email = email;
  this.phone = phone;
 }

 @Override
 public boolean equals(Object emp) {
  if (emp instanceof Student) {
   Student student = (Student) emp;

   if (this.firstname.equals(student.getFirstname())
     && this.lastname.equals(student.getLastname())
     && this.email.equals(student.getEmail())
     && this.phone.equals(student.getPhone()))
    return true;
  }

  return false;
 }

 @Override
 public int hashCode() {

  return this.firstname.hashCode() + this.lastname.hashCode()
    + this.email.hashCode() + this.phone.hashCode();
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public Long getStudentId() {
  return studentId;
 }

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

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

 public Set<Test> getTest() {
  return test;
 }

 public void setTest(Set<Test> test) {
  this.test = test;
 }
}



\src\main\java\com\beingjavaguys\domain\Test.java

package com.beingjavaguys.domain;

import java.util.Date;
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 = "TEST")
public class Test {

 @Id
 @Column(name = "TEST_ID")
 @GeneratedValue
 private Long testId;

 @Column(name = "SUBJECT")
 private String subject;

 @Column(name = "MAX_MARKS")
 private String maxMarks;

 @Column(name = "MARKS_OBTAINED")
 private String marksObtained;

 @Column(name = "RESULT")
 private String result;

 @ManyToMany(mappedBy = "test")
 private Set<Student> student = new HashSet<Student>();

 public Test(String subject, String maxMarks, String marksObtained,
   String result) {
  this.subject = subject;
  this.maxMarks = maxMarks;
  this.marksObtained = marksObtained;
  this.result = result;

 }

 public String getSubject() {
  return subject;
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }

 public Long getTestId() {
  return testId;
 }

 public void setTestId(Long testId) {
  this.testId = testId;
 }

 public String getMaxMarks() {
  return maxMarks;
 }

 public void setMaxMarks(String maxMarks) {
  this.maxMarks = maxMarks;
 }

 public String getMarksObtained() {
  return marksObtained;
 }

 public void setMarksObtained(String marksObtained) {
  this.marksObtained = marksObtained;
 }

 public String getResult() {
  return result;
 }

 public void setResult(String result) {
  this.result = result;
 }

 public Set<Student> getStudent() {
  return student;
 }

 public void setStudent(Set<Student> student) {
  this.student = student;
 }

}



\src\main\java\com\beingjavaguys\hbn\HibernateUtils.java

package com.beingjavaguys.hbn;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtils {

 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new AnnotationConfiguration().configure()
     .buildSessionFactory();
  } catch (Throwable ex) {
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}



Implementation class code

\src\main\java\com\beingjavaguys\hbn\App.java

package com.beingjavaguys.hbn;

/**
 * @author Nagesh Chauhan
 *
 */
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.beingjavaguys.domain.Student;
import com.beingjavaguys.domain.Test;

public class App {
 public static void main(String[] args) {
  SessionFactory sf = HibernateUtils.getSessionFactory();
  Session session = sf.openSession();

  session.beginTransaction();

  Student student1 = new Student("Nagesh", "Chauhan",
    "beingjavaguy@gmail.com", "8789876765");
  Student student2 = new Student("Shweta", "Chauhan", "shweta@gmail.com",
    "8767598786");

  Test test1 = new Test("Maths", "100", "87", "Passed");
  Test test2 = new Test("Science", "100", "90", "Passed");

  student1.getTest().add(test1);
  student1.getTest().add(test2);
  student2.getTest().add(test1);
  student2.getTest().add(test2);

  session.save(student1);
  session.save(student2);

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



Table structure after implementation





In this particular blog we came across 'Hibernate Many to Many mapping and, implementation using annotations'. In upcoming blogs we will see more about 'Hibernate' and Other opensource technologies.








Thanks for reading !
Being Java Guys Team

Download "Hibernate Many to Many Mapping Example Project" from "SkyDrive"





1 comment:

  1. Ratnesh Chandak12 June 2015 at 22:36

    How do i enter data in my student_test table when i am adding test, shall i have to take student_id from user, and also create student_test repository to save student_id & test_id or shall i take student_id and test_id differently/from different user request and save them in table through repository

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft