Hibernate Many To Many Mapping
By AmarSivas | | Updated : 2021-09-25 | Viewed : 207 times

We glance here at Hibernate Many To Many Mapping with a nice example.
Table of Contents:
ManyToMany Association
When the one table record is associated with many records of another table and vice versa then this type of association is said to be a
Consider the example relation between
Please notice the below-given diagram for the same.

ManyToMany Example with Join Table
Database Setup
Create below-given tables for implementation of many to many associations.
CREATE TABLE `author_1` (
`AUTHOR_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`AUTHOR_NAME` VARCHAR(50) NOT NULL,
PRIMARY KEY (`AUTHOR_ID`)
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
AUTO_INCREMENT=7;
CREATE TABLE `book_1` (
`BOOK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`BOOK_NAME` VARCHAR(50) NOT NULL,
`BOOK_PRICE` DOUBLE NULL DEFAULT NULL,
`BOOK_TYPE` VARCHAR(50) NOT NULL,
PRIMARY KEY (`BOOK_ID`)
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
AUTO_INCREMENT=90;
CREATE TABLE `author_book_1` (
`AUTHOR_BOOK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`AUTHOR_ID` INT(10) UNSIGNED NOT NULL,
`BOOK_ID` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`AUTHOR_BOOK_ID`),
INDEX `AUTHOR_ID` (`AUTHOR_ID`),
INDEX `BOOK_ID` (`BOOK_ID`),
CONSTRAINT `AUTHOR_FK` FOREIGN KEY (`AUTHOR_ID`) REFERENCES `author_1` (`author_id`),
CONSTRAINT `BOOK_FK` FOREIGN KEY (`BOOK_ID`) REFERENCES `book_1` (`book_id`)
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
AUTO_INCREMENT=11;
Write Entity Classes
Notice below given Entity classes for many to many relationship examples.
@Entity
@Table(name = "AUTHOR_1")
@Getter
@Setter
@AllArgsConstructor
public class Author {
//remaining properties
@ManyToMany(cascade= CascadeType.ALL)
@JoinTable(name="author_book_1", joinColumns={@JoinColumn(name="AUTHOR_ID", referencedColumnName="AUTHOR_ID")}
, inverseJoinColumns={@JoinColumn(name="BOOK_ID", referencedColumnName="BOOK_ID")})
private Set<Book> Books;
}
@Entity
@Table(name = "BOOK_1")
@Getter
@Setter
public class Book {
//remaining properties
}
@Entity
@Table(name = "author_book_1")
@Getter
@Setter
public class AuthorBook {
//remaining properties
}
Saving/Retrieving Entities
Save the data using the below-given client. Please notice below the given code snippet.
public class MainClient {
public static void main(String[] args) {
System.out.println("Main method@MainClient");
// obtains the session
Author author = new Author("Author1");
Book book1 = new Book("Book1", 100.0,"Fiction");
Book book2 = new Book("Book2", 200.0,"NonFiction");
Book book3 = new Book("Book3", 300.0,"Fiction");
Set<Book> books = new HashSet<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
author.setBooks(books);
try {
// Get Session
Session session = HibernateUtil.getSessionFactory().openSession();
System.out.println("Session is created");
// start transaction
Transaction tx = session.beginTransaction();
// Save the Model objects
session.save(author);
session.getTransaction().commit();
session.close();
System.out.println("Session is closed");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please find the Github repo Hibernate-ManytoMany-Association-JoinTable-Annotation-Example-App