0
Sponsored Links


Ad by Google
In this post we are going to show you how to use Many-To-Many association in hibernate using annotation. For One-To-Many association example you can traverse my previous post One-To-Many association example using annotation.
Many-To-Many association means, One or more row(s) of a table are associated one or more row(s) in another table. For example an employee may assigned with multiple projects, and a project is associated with multiple employees.
In this post we are going to show you the same employee and project association using annotation, below are the listed table for our this project.

Employee table:
employee_id first_name last_name doj
101 Tony Jha 2014-08-28
102 Zeneva S. Humphrey 2014-07-04

Project table:
project_id project_name start_date exp_end_date
101 MARS 2013-01-01 2015-08-28
102 SBA 2014-10-02 2016-07-04

Employee_Proj table:
employee_id project_id
101 101
101 102
102 102

From the above Employee_Proj table it's clear that an employee 101 is associated with project(101,102) and project 102 is associated with employee(101,102). So it's clear that employee and project relationship is fall in Many-To-Many association categories. Oh it's too late lets start implementing in Hibernate.

Here is Many-To-Many association mapping table ER diagram.

Tools and Technologies we are using here:

  • JDK 7
  • Hibernate 4.3.7
  • MySql 5.1.10
  • Eclipse Juno 4.2
  • Maven 3.2
Overview of the Project Structure:


Main Objects of this project are:
  • pom.xml
  • hibernate.cfg.xml
  • annotated pojo
  • database

Step 1. Create database script.

CREATE DATABASE /*!32312 IF NOT EXISTS*/`hibernate_tutorial`

USE `hibernate_tutorial`;

/*Table structure for table `employee` */

DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
  `employee_id` int(11) NOT NULL AUTO_INCREMENT,
  `doj` date DEFAULT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;

/*Table structure for table `project` */

DROP TABLE IF EXISTS `project`;

CREATE TABLE `project` (
  `project_id` int(11) NOT NULL AUTO_INCREMENT,
  `exp_end_date` date DEFAULT NULL,
  `project_name` varchar(255) DEFAULT NULL,
  `start_date` date DEFAULT NULL,
  PRIMARY KEY (`project_id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;

Step 2. Create a Maven Project:
Step A: Go to File->New->Other..


Step B: Select Maven Project from the select wizard.


Step C: Select project name and location from New Maven Project wizard.


Step D: Configure project, provide GroupId, artifactId etc. See the details from the screenshot. This screen shot is from our previous post so here you need to change the artifactId as Many-To-Many-Association-Example.


Step E: After completion of all the above steps, now your project will looks like this screenshot.



3. Add project dependencies into pom.xml file:
Double click on your project's pom.xml file it will looks like this with very limited information.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hibernate.poc</groupId>
  <artifactId>Many-To-Many-Annotation-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Many-To-Many-Annotation-Example</name>
  
</project>

Now add Hibernate and MySql dependencies entry inside pom.xml file. Paste the below code inside the project tag of pom.xml file.
<dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>

 </dependencies>


Here is a complete pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hibernate.poc</groupId>
  <artifactId>Many-To-Many-Annotation-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Many-To-Many-Annotation-Example</name>
  
  <dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>

 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

4. Create a hibernate.cfg.xml file:
Create hibernate.cfg.xml file inside src/main/resources folder.

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/hibernate_tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
         
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.hibernate.association.pojo.Employee"/>
        <mapping class="com.hibernate.association.pojo.Project"/>
          
    </session-factory>
</hibernate-configuration>


Step 5. Create an Employee annotated class:

package com.hibernate.association.pojo;

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "employee")
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "employee_id")
 private int employeeId;

 @Column(name = "first_name")
 private String firstName;

 @Column(name = "last_name")
 private String lastName;

 @Column(name = "doj")
 @Temporal(TemporalType.DATE)
 private Date doj;

 @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
 @JoinTable(name = "employee_proj", joinColumns = { 
   @JoinColumn(name = "employee_id", nullable = false, updatable = false) },
   inverseJoinColumns = { @JoinColumn(name = "project_id", nullable = false, updatable = false) })
 private Set<Project> projects;

 public int getEmployeeId() {
  return employeeId;
 }

 public void setEmployeeId(int employeeId) {
  this.employeeId = employeeId;
 }

 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 Date getDoj() {
  return doj;
 }

 public void setDoj(Date doj) {
  this.doj = doj;
 }

 public Set<Project> getProjects() {
  return projects;
 }

 public void setProjects(Set<Project> projects) {
  this.projects = projects;
 }

 @Override
 public String toString() {
  return "Employee [employeeId=" + employeeId + ", firstName="
    + firstName + ", lastName=" + lastName + ", doj=" + doj
    + ", projects=" + projects + "]";
 }

}

Step 6. Create Project annotated class:

package com.hibernate.association.pojo;

import java.util.Date;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "project")
public class Project {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "project_id")
 private int projectId;

 @Column(name = "project_name")
 private String projectName;

 @Column(name = "start_date")
 @Temporal(TemporalType.DATE)
 private Date startDate;

 @Column(name = "exp_end_date")
 @Temporal(TemporalType.DATE)
 private Date expectedEndDate;

 @ManyToMany(fetch = FetchType.LAZY, mappedBy = "projects")
 private Set<Employee> employees;

 public int getProjectId() {
  return projectId;
 }

 public void setProjectId(int projectId) {
  this.projectId = projectId;
 }

 public String getProjectName() {
  return projectName;
 }

 public void setProjectName(String projectName) {
  this.projectName = projectName;
 }

 public Date getStartDate() {
  return startDate;
 }

 public void setStartDate(Date startDate) {
  this.startDate = startDate;
 }

 public Date getExpectedEndDate() {
  return expectedEndDate;
 }

 public void setExpectedEndDate(Date expectedEndDate) {
  this.expectedEndDate = expectedEndDate;
 }

 public Set<Employee> getEmployees() {
  return employees;
 }

 public void setEmployees(Set<Employee> employees) {
  this.employees = employees;
 }

 @Override
 public String toString() {
  return "Project [projectId=" + projectId + ", projectName="
    + projectName + ", startDate=" + startDate
    + ", expectedEndDate=" + expectedEndDate + ", employees="
    + employees + "]";
 }

}

Step 7. Create a HibernateUtility class: HibernateUtility class to build SessionFactory via loading Configuration file.

package com.hibernate.association.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtility {
 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
  Configuration configuration = new Configuration();
  configuration.configure();

  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .applySettings(configuration.getProperties()).build();
  SessionFactory sessionFactory = configuration
    .buildSessionFactory(serviceRegistry);
  return sessionFactory;
 }

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

Step 8. Create an EmployeeDAO class: to perform insert/update/get/delete records into the database.

package com.hibernate.association.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.hibernate.association.pojo.Employee;
import com.hibernate.association.util.HibernateUtility;

public class EmployeeDAO {
 private static SessionFactory sessionFactory;
 static {
  sessionFactory = HibernateUtility.getSessionFactory();
 }

 public static Employee findById(long id) {
  Session session = sessionFactory.openSession();
  Employee employee = (Employee) session.load(Employee.class, id);

  return employee;
 }

 public static Employee save(Employee employee) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.save(employee);

  session.getTransaction().commit();

  return employee;
 }

 public static Employee update(Employee employee) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.merge(employee);

  session.getTransaction().commit();

  return employee;

 }

 public static void delete(Employee employee) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.delete(employee);

  session.getTransaction().commit();

 }
}

Step 9. Create an EmployeeService class: to call the methods of EmployeeDAO class to perform CRUD.

package com.hibernate.association.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import com.hibernate.association.dao.EmployeeDAO;
import com.hibernate.association.pojo.Employee;
import com.hibernate.association.pojo.Project;

public class EmployeeService {
 public static void main(String[] args) {
  Employee employee = new Employee();

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  try {
   // employee details
   employee.setDoj(sdf.parse("2014-08-28"));
   employee.setFirstName("Tony");
   employee.setLastName("Jha");

   // project details
   Project mars = new Project();
   mars.setProjectName("MARS");
   mars.setStartDate(sdf.parse("2013-01-01"));
   mars.setExpectedEndDate(sdf.parse("2015-08-28"));

   // project 2 details
   Project sba = new Project();
   sba.setProjectName("SBA");
   sba.setStartDate(sdf.parse("2014-10-02"));
   sba.setExpectedEndDate(sdf.parse("2016-07-04"));

   Set<Project> projects = new HashSet<>();
   projects.add(mars);
   projects.add(sba);

   employee.setProjects(projects);
   // calling save method of EmployeeDAO
   System.out.println(EmployeeDAO.save(employee));

  } catch (ParseException e) {
   e.printStackTrace();
  }

 }
}

That's it. Run EmployeeService and see the output, one insert query for employee two insert query for project and two for employee_proj table.

OUT PUT:
Hibernate: 
    insert 
    into
        employee
        (doj, first_name, last_name) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        project
        (exp_end_date, project_name, start_date) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        project
        (exp_end_date, project_name, start_date) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        employee_proj
        (employee_id, project_id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        employee_proj
        (employee_id, project_id) 
    values
        (?, ?)

String message printed by toString()method of Employee class,

Employee [employeeId=101, firstName=Tony, lastName=Jha, doj=Thu Aug 28 00:00:00 IST 2014, projects=[Project [projectId=102, projectName=SBA, startDate=Thu Oct 02 00:00:00 IST 2014, expectedEndDate=Mon Jul 04 00:00:00 IST 2016, employees=null], Project [projectId=101, projectName=MARS, startDate=Tue Jan 01 00:00:00 IST 2013, expectedEndDate=Fri Aug 28 00:00:00 IST 2015, employees=null]]]

Download the complete example from here Source Code


Sponsored Links

0 comments:

Post a Comment