Hibernate Many To Many Mapping

By | | Updated : 2021-09-25 | Viewed : 75 times

Hibernate Many To Many Mapping

We glance here at Hibernate Many To Many Mapping with a nice example.

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 many-to-many relationship. In between these two tables, there will be another table for maintaining the association.

Consider the example relation between Author and Book. So one Author can write many books and one Book can be written by many authors. So Author can be associated with many books and vice versa. So these types of relationships are handled well in the hibernate. We will look at that example.

Please notice the below-given diagram for the same.

ManyToMany Association

ManyToMany Example with Join Table

Database Setup

Create below-given tables for implementation of many to many associations.

DataBase set up for Many To Many relationships
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.

Author.java
@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;

}
Book.java
@Entity
@Table(name = "BOOK_1")
@Getter
@Setter
public class Book {
	//remaining properties
}
AuthorBook.java
@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.

MainClient.java
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();
		}

	}
}
Leave A Reply