Hibernate Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example

In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to many (items) and vice-versa as it is a bidirectional mapping.

Here, we are creating an example of many-to-many association mapping. In this example, we need to specify @ManyToMany and @JoinTable annotations in the persistent class. Here, we need to take a collection property like Set, Map, Bag, and List in both persistent classes.

Following are the steps to create the example:

  1. Create all Persistent classes

In this step, we are going to develop persistent classes, i.e., Categories.java and Items.java.

Categories.java

import java.util.Set;
 import javax.persistence.CascadeType;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id; 
 import javax.persistence.JoinColumn;
 import javax.persistence.JoinTable;
 import javax.persistence.ManyToMany;
 import javax.persistence.Table;
 @Entity 
 @Table(name="categories")
 public class Categories {
  @Id
  @Column(name="c_id")
  private int cate_id;
  @Column(name="c_name") 
  private String cate_name;
  @ManyToMany(targetEntity=Items.class, cascade=CascadeType.ALL)
  @JoinTable(name="cate_items",joinColumns=@JoinColumn(name="c_id_fk",referencedColumnName="c_id"),inverseJoinColumns=@JoinColumn(name="item_id_fk",referencedColumnName="i_id")) 
  private Set items;
  public int getCate_id() {
  return cate_id;
  } 
  public void setCate_id(int cate_id) {
  this.cate_id = cate_id;
  }
  public String getCate_name() { 
  public void setCate_id(int cate_id) {
  this.cate_id = cate_id;
  }
  public String getCate_name() {
  return cate_name; 
  }
  public void setCate_name(String cate_name) {
  this.cate_name = cate_name;
  }
  public Set getItems() {
  return items; 
  }
  public void setItems(Set items) {
  this.items = items;
  }
  } 

Items.java

import java.util.Set;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.ManyToMany;
 import javax.persistence.Table; 
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.ManyToMany;
 import javax.persistence.Table; 
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.ManyToMany;
 import javax.persistence.Table; 
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.ManyToMany;
 import javax.persistence.Table; 
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.ManyToMany;
 import javax.persistence.Table;
 @Entity
 @Table(name="items")
 public class Items {
  @Id
  @Column(name="i_id")
  private int item_id;
  @Column(name="i_name")  
  private String item_name;
  @ManyToMany(targetEntity=Categories.class,mappedBy="items")
  private Set categories;
  public int getItem_id() {
  return item_id;
  } 
  public void setItem_id(int item_id) {
  this.item_id = item_id;
  }
  public String getItem_name() {
  return item_name;
  } 
  public void setItem_name(String item_name) {
  this.item_name = item_name;
  }
  public Set getCategories() {
  return categories;
  }
  public void setCategories(Set categories) { 
  this.categories = categories;
  }
  } 
  • Create the configuration file

In this step, we are going to create the configuration class (hibernate.cfg.xml) which contains the information of persistent class and the database.

hibernate.cfg.xml

 
  
  
   
 update 
 org.hibernate.dialect.MySQL5Dialect
 com.mysql.jdbc.Driver
 jdbc:mysql://localhost:3306/test
 root
 root 
  
  
  
   
  • Create the main class that stores the object of the persistent class

In this step, we are going to create a class which consists of main() method, and stores the objects of persistent classes.

App.java

import java.util.HashSet;
 import java.util.Set;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 public class App  
 {
  public static void main( String[] args )
  {
  Configuration cfg= new Configuration();
  cfg.configure("hibernate.cfg.xml");
  SessionFactory factory = cfg.buildSessionFactory(); 
  Session session= factory.openSession();
  Categories cate1 = new Categories();
  cate1.setCate_id(01);
  cate1.setCate_name("category 01");
  Categories cate2 = new Categories();
  cate2.setCate_id(02); 
  cate2.setCate_name("category 02");
  Items i= new Items();
  i.setItem_id(31);
  i.setItem_name("item 11");
  Items i2 =new Items();
  i2.setItem_id(32);
  i2.setItem_name("item 21"); 
  Set set= new HashSet();
  set.add(i);
  set.add(i2);
  cate1.setItems(set);
  cate2.setItems(set);
  Transaction t= session.beginTransaction(); 
  session.save(cate1);
  session.save(cate2);
  t.commit();
  System.out.println("saved successfully!!!!");
  session.close();
  }
 } 
  • Output
Many-to-Many Hibernate Mapping
  • Database tables

categories table

categories table Many-to-Many Hibernate Mapping

items table

items table Many-to-Many Hibernate Mapping

cate_items table

cate_items table Many-to-Many Hibernate Mapping

Related Topics

Hibernate Composite Primary Key

Hibernate Composite Primary Key A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is...

8 minutes read.

Hibernate History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.

Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using...

3 minutes read.

Hibernate Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.

Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database. Session.get() The session.get() method is used to fetch a persistent object of the...

2 minutes read.

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate Annotation with Example

Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases and it also uses the specifications of the...

2 minutes read.

Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

3 minutes read.

Hibernate Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

3 minutes read.

Hibernate Named Query using Annotation

In annotation-based named query, we use @NamedQuery annotation inside the POJO class. @NamedQuery- It is used to describe a single named query. It consists of four attributes- two of which are compulsory, and...

2 minutes read.

Hibernate first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 minutes read.

Hibernate vs. JPA

What is JPA? JPA stands for Java Persistence API, which defines a set of functionalities, standards, and concepts to the ORM tool. It is a framework used to manage relational databases. It is available...

2 minutes read.

Hibernate SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

3 minutes read.

Hibernate Criteria Query Language (HCQL)

Hibernate Criteria Query Language (HCQL) is mainly used for searching and fetching records. It works on the filtration rules and logical conditions. The Criteria interface, Restriction class, and Order class are available in...

4 minutes read.

Hibernate Inheritance Table Per Class

In this inheritance strategy, table per class is generated. It means a separate table is generated for each POJO class involved in the hierarchy. Unlike the SINGLE_TABLE strategy, there are no nullable values...

3 minutes read.

Hibernate Session Interface

Hibernate Session Interface A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it...

4 minutes read.

Hibernate Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 minutes read.

Hibernate vs. JDBC

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

2 minutes read.

Hibernate Configuration Properties

Hibernate Configuration Hibernate Configuration is a Java class, which allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad...

6 minutes read.

Hibernate Many-to-One Mapping

Many-to-One Hibernate Mapping with Example A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class...

3 minutes read.