Many to Many relationship can occur in relational database, when one record in the parent table refer the several records in the child table and vice versa. In hibernate many to many mapping is made between the two entities, where one can have relation with multiple other entities.

Hibernate Many to Many Mapping :

Lets see with the example, if we consider the Book and Author entities. We can assume like, an Author can write multiple Books and a Book may written by multiple Authors. So here, we can say that Book and Author entities has many to many relationship. And we can also say that, a many to many relationship is a combination of one to many relationships from the both entities point of view.

In this tutorial, we are going to implement hibernate many to many relationship using xml configuration.

Hibernate Many to Many Mapping Example :

Project Structure :

Hibernate Many to Many Mapping

Required Dependencies :

pom.xml

pom.xml
<dependencies>
            <!-- Hibernate -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.3.0.Final</version>
            </dependency>
            <!-- MySQL Driver -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.0.5</version>
            </dependency>
 </dependencies>

Hibernate POJO Classes :

Book.java

Book.java
package com.onlinetutorialspoint.hibernate.pojo;

import java.util.List;

public class Book {

    private int bookId;
    private String bookName;
    private String isbnCode;
    private List authors;

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getIsbnCode() {
        return isbnCode;
    }

    public void setIsbnCode(String isbnCode) {
        this.isbnCode = isbnCode;
    }

    public List getAuthors() {
        return authors;
    }

    public void setAuthors(List authors) {
        this.authors = authors;
    }

}
In Hibernate, if a relationship ends with To-Many then we need a reference variable of type Collection (List, Set or Map) in parent class.So that on the above Book class, we took the List collection to store the authors.

Author.java

Author.java
package com.onlinetutorialspoint.hibernate.pojo;

import java.util.Set;

public class Author {

    private int authorId;
    private String authorName;
    private String authorAddress;
    private Set books;

    public int getAuthorId() {
        return authorId;
    }

    public void setAuthorId(int authorId) {
        this.authorId = authorId;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getAuthorAddress() {
        return authorAddress;
    }

    public void setAuthorAddress(String authorAddress) {
        this.authorAddress = authorAddress;
    }

    public Set getBooks() {
        return books;
    }

    public void setBooks(Set books) {
        this.books = books;
    }

}

Note: The relationship between the Author to Book also One to Many. So that we took Set Collection in Author class to store the authors list.

Hibernate Mapping Files :

book.hbm.xml

book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.onlinetutorialspoint.hibernate.pojo.Book" table="book">
        <id name="bookId" column="bookid" />
        <property name="bookName" column="bookname" />
        <property name="isbnCode" column="isbncode" />

        <idbag name="authors" table="author_books" cascade="all">
            <collection-id type="int" column="book_author_id">
                <generator class="increment"></generator>
            </collection-id>
            <key column="bid_fk" />
            <many-to-many class="com.onlinetutorialspoint.hibernate.pojo.Author"
                column="aid_fk" />
        </idbag>
    </class>
</hibernate-mapping>

As per the fifth normal form, when ever the many to many relationship occurs between the two components, we need to take the another table to join the two entities. That table is usually called as join table. Above is the hibernate many to many relationship configuration.

author.hbm.xml

author.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.onlinetutorialspoint.hibernate.pojo.Author"
        table="author">
        <id name="authorId" column="authorid" />
        <property name="authorName" column="name" />
        <property name="authorAddress" column="address" />
        <set name="books" table="author_books" cascade="all">
            <key column="aid_fk" />
            <many-to-many class="com.onlinetutorialspoint.hibernate.pojo.Book"
                column="bid_fk" />
        </set>
    </class>
</hibernate-mapping>

Lets Run the Example :

Main.java

Main.java
import java.util.ArrayList;

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

import com.onlinetutorialspoint.hibernate.pojo.Author;
import com.onlinetutorialspoint.hibernate.pojo.Book;
import com.onlinetutorialspoint.util.HibernateUtil;

public class Main {

public static void main(String a[])
{

SessionFactory sessionFactory = HibernateUtil.getInstnce();
Session session = sessionFactory.openSession();

Book book=new Book();
book.setBookId(101);
book.setBookName("java");
book.setIsbnCode("201");

Book book2=new Book();
book2.setBookId(102);
book2.setBookName("C++");
book2.setIsbnCode("202");

Author author1=new Author();
author1.setAuthorId(1001);
author1.setAuthorName("John");
author1.setAuthorAddress("hyd");

Author author2=new Author();
author2.setAuthorId(1002);
author2.setAuthorName("Robert");
author2.setAuthorAddress("hyd");

ArrayList authorsList=new ArrayList();

authorsList.add(author1);
authorsList.add(author2);
book.setAuthors(authorsList);
book2.setAuthors(authorsList);

Transaction transaction=session.beginTransaction();

session.save(book);
session.save(book2);

transaction.commit();

session.close();
sessionFactory.close();
}

}

Output :

Terminal
Hibernate: select author_.authorid, author_.name as name2_0_, author_.address as address3_0_ from author author_ where author_.authorid=?
Hibernate: select author_.authorid, author_.name as name2_0_, author_.address as address3_0_ from author author_ where author_.authorid=?
Hibernate: insert into book (bookname, isbncode, bookid) values (?, ?, ?)
Hibernate: insert into author (name, address, authorid) values (?, ?, ?)
Hibernate: insert into author (name, address, authorid) values (?, ?, ?)
Hibernate: insert into book (bookname, isbncode, bookid) values (?, ?, ?)
Hibernate: select max(book_author_id) from author_books
Hibernate: insert into author_books (bid_fk, book_author_id, aid_fk) values (?, ?, ?)
Hibernate: insert into author_books (bid_fk, book_author_id, aid_fk) values (?, ?, ?)
Hibernate: insert into author_books (bid_fk, book_author_id, aid_fk) values (?, ?, ?)
Hibernate: insert into author_books (bid_fk, book_author_id, aid_fk) values (?, ?, ?)

Database Output :

Many to Many Hiberanate

Happy Learning 🙂

Download Example