JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Hibernate Many-to-Many mapping example using @ManyToMany annotation.


In our database we create many tables and many of them may be associated with each other. At higher lever, these associations can be classified into one-to-one, one-to-many and many-to-many. These associations can be either unidirectional or bidirectional mappings. Hibernate provides support to all these associations.

In this page, we see how to implement bidirectional Many-to-Many mapping between persisted objects using @ManyToMany annotation.

A many-to-many relationship occurs when multiple entities are related to multiple occurrences of another entity.

Create DB Table

Here is our DB tables. Our tables are already Many-to-Many mapped. We have created EMPLOYEES, PROJECTS, and EMP_ASSIGNMENTS tables.

CREATE TABLE EMPLOYEES (

	EMP_ID BIGINT NOT NULL AUTO_INCREMENT,
	NAME VARCHAR(252),
	DEPARTMENT VARCHAR(128),
	SALARY BIGINT,
	JOINED_ON TIMESTAMP,
	PRIMARY KEY (EMP_ID)
);

CREATE TABLE PROJECTS (

	PR_ID BIGINT NOT NULL AUTO_INCREMENT,
	NAME VARCHAR(252),
	OWNER VARCHAR(252),
	PRIMARY KEY (PR_ID)
);

CREATE TABLE EMP_ASSIGNMENTS (

	EA_ID BIGINT NOT NULL AUTO_INCREMENT,
	EMP_ID BIGINT,
	PR_ID BIGINT,
	PRIMARY KEY (EA_ID),
	FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEES(EMP_ID),
	FOREIGN KEY (PR_ID) REFERENCES PROJECTS(PR_ID)
);

INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (1, 'Nataraja G', 'Documentation', 10000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (2, 'Amar M', 'Entertainment', 12000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (3, 'Nagesh Y', 'Admin', 25000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (4, 'Vasu V', 'Security', 2500, CURRENT_TIMESTAMP);

INSERT INTO PROJECTS (PR_ID, NAME, OWNER) VALUES (1, 'Ticket Online', 'Bunty');
INSERT INTO PROJECTS (PR_ID, NAME, OWNER) VALUES (2, 'Disco Drum', 'Chanty');
INSERT INTO PROJECTS (PR_ID, NAME, OWNER) VALUES (3, 'Traffic Audit', 'Sonty');

INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (1, 1, 1);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (2, 1, 2);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (3, 1, 3);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (4, 2, 2);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (5, 2, 3);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (6, 3, 1);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (7, 3, 3);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (8, 4, 1);
INSERT INTO EMP_ASSIGNMENTS (EA_ID, EMP_ID, PR_ID) VALUES (9, 3, 2);

Hibernate Configuration File

Create hibernate xml based configuration file in your resources folder (classpath). This file includes hibernate configurations like driver class, DB connectivity URL, DB credentials and so on...

j2n-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>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java2novice</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="show_sql">false</property>
	</session-factory>
</hibernate-configuration>

Hibernate Mapping with Entity Class

Here is the entity classes according to our database tables along with Many-to-Many mappings.

package com.java2novice.model;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

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;

@Entity
@Table(name="EMPLOYEES")
public class Employee implements Serializable {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="EMP_ID", unique = true, nullable = false)
	private Long empId;

	private String name;

	private String department;

	private Long salary;

	@Column(name="JOINED_ON")
	private Date joinedOn;

	@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
	@JoinTable(
		name = "EMP_ASSIGNMENTS",
		joinColumns = { @JoinColumn(name = "EMP_ID") },
		inverseJoinColumns = { @JoinColumn(name = "PR_ID") }
	)
	private List<Project> empAssignmentList;

	public Long getEmpId() {
		return empId;
	}

	public void setEmpId(Long empId) {
		this.empId = empId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public Long getSalary() {
		return salary;
	}

	public void setSalary(Long salary) {
		this.salary = salary;
	}

	public Date getJoinedOn() {
		return joinedOn;
	}

	public void setJoinedOn(Date joinedOn) {
		this.joinedOn = joinedOn;
	}

	public List<Project> getEmpAssignmentList() {
		return empAssignmentList;
	}

	public void setEmpAssignmentList(List<Project> empAssignmentList) {
		this.empAssignmentList = empAssignmentList;
	}

	@Override
	public String toString() {

		String resp = this.empId+" | "+this.name+" | "+this.department+" | "+this.salary+" | "+this.joinedOn;

		return resp;
	}
}

package com.java2novice.model;

import java.util.List;

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

@Entity
@Table(name="PROJECTS")
public class Project {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="PR_ID", unique = true, nullable = false)
	private Long prId;

	private String name;

	private String owner;

	@ManyToMany(mappedBy = "empAssignmentList")
	private List<Employee> employees;

	@Override
	public String toString() {

		return this.prId +" | "+ this.name +" | "+ this.owner;
	}

	public Long getPrId() {
		return prId;
	}

	public void setPrId(Long prId) {
		this.prId = prId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}
}

Hibernate Utility Class

This class manages hibernate session.

package com.java2novice.hibernate;

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

import com.java2novice.model.Employee;
import com.java2novice.model.Project;

public class HibernateUtil {

	private static SessionFactory sessionFactory = null;

	static {
		try{
			loadSessionFactory();
		}catch(Exception e){
			System.err.println("Exception while initializing hibernate util.. ");
			e.printStackTrace();
		}
	}

	public static void loadSessionFactory(){

		Configuration configuration = new Configuration();
		configuration.configure("/j2n-hibernate.cfg.xml");
		configuration.addAnnotatedClass(Employee.class);
		configuration.addAnnotatedClass(Project.class);
		ServiceRegistry srvcReg = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(srvcReg);
	}

	public static Session getSession() throws HibernateException {

		Session retSession=null;
	    	try {
	    		retSession = sessionFactory.openSession();
	    	}catch(Throwable t){
			System.err.println("Exception while getting session.. ");
			t.printStackTrace();
	    	}
	    	if(retSession == null) {
	    		System.err.println("session is discovered null");
	    	}

	    	return retSession;
    }
}

Hibernate Dao Class

package com.java2novice.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.java2novice.model.Employee;

public class EmployeesDao {

	public List<Employee> getEmployeeList(){

		Session session = null;
		List<Employee> empList = null;
		try {
			session = HibernateUtil.getSession();
			String queryStr = "select emp from Employee emp";
			Query query = session.createQuery(queryStr);
			empList = query.list();
		} catch(Exception ex) {
			ex.printStackTrace();
			// handle exception here
		} finally {
			try {if(session != null) session.close();} catch(Exception ex) {}
		}
		return empList;
	}

	public static void main(String a[]) {

		EmployeesDao empDao = new EmployeesDao();
		List<Employee> empList = empDao.getEmployeeList();
		System.out.println("emp size: "+empList.size());
		System.out.println("---------------------------");
		empList.stream().forEach(e -> {
			System.out.println(e);
			System.out.println("\n-- projects assigned to "+e.getName()+" --");
			e.getEmpAssignmentList().stream().forEach(System.out::println);
			System.out.println("---------------------------");
		});
	}
}

Output:
emp size: 4
---------------------------
1 | Nataraja G | Documentation | 10000 | 2017-12-16 11:59:59.0

-- projects assigned to Nataraja G --
1 | Ticket Online | Bunty
2 | Disco Drum | Chanty
3 | Traffic Audit | Sonty
---------------------------
2 | Amar M | Entertainment | 12000 | 2017-12-16 11:59:59.0

-- projects assigned to Amar M --
2 | Disco Drum | Chanty
3 | Traffic Audit | Sonty
---------------------------
3 | Nagesh Y | Admin | 25000 | 2017-12-16 11:59:59.0

-- projects assigned to Nagesh Y --
1 | Ticket Online | Bunty
2 | Disco Drum | Chanty
3 | Traffic Audit | Sonty
---------------------------
4 | Vasu V | Security | 2500 | 2017-12-16 12:00:21.0

-- projects assigned to Vasu V --
1 | Ticket Online | Bunty
---------------------------
<< Previous Program | Next Program >>

Hibernate Examples

  1. Hibernate hello world (initial setup) example.
  2. What is hibernate.cfg.xml configuration?
  3. What are the basic hibernate persistent annotations?
  4. What is SessionFactory in Hibernate?
  5. What is Session object in Hibernate?
  6. List Hibernate Session interface methods.
  7. What is Hibernate Query object?
  8. Basic Hibernate CRUD operations example.
  9. Hibernate Bidirectional One-to-One mapping using @OneToOne annotation.
  10. Hibernate Unidirectional One-to-One mapping using @OneToOne annotation.
  11. Hibernate Eager vs Lazy Fetch Type
  12. Hibernate Unidirectional One-to-Many mapping using @OneToMany annotation.
  13. Hibernate Bidirectional One-to-Many mapping using @OneToMany annotation.
  14. Hibernate Many-to-Many mapping example using @ManyToMany annotation.
  15. How to enable logging (log4j) in Hibernate?
Knowledge Centre
What is servlet context?
The servlet context is an interface which helps to communicate with other servlets. It contains information about the Web application and container. It is kind of application environment. Using the context, a servlet can obtain URL references to resources, and store attributes that other servlets in the context can use.
Famous Quotations
Tomorrow is often the busiest day of the week.
-- Spanish Proverb

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.