Hibernate – @ManyToMany Annotation
Last Updated :
21 Jun, 2023
@ManyToMany annotation in Hibernate is used to obtain many-to-many relationships between two entities. It allows us to create a bidirectional relationship between two entities where each entity can be associated with another entity through multiple instances.
Examples of @ManyToMany Annotation
Example 1:
Java
@Entity
public class Student {
@Id
@GeneratedValue
private long id;
private String name;
@ManyToMany
private ArrayList<Course> courses;
}
@Entity
public class Course {
@Id
@GeneratedValue
private long id;
private String courseName;
private int courseDuration;
@ManyToMany
private ArrayList<Student> students;
}
|
Code Explanation:
In the above example, we are creating two entities named a Student and Course. The student entity has different fields within it such as id, name of student, and the array of courses in which the student is enrolled. The array list of students is annotated with @ManyToMany. Similarly, we are creating an entity for the Course which has several fields such as id, course name, course duration, and the array of students who have registered for this course. We are also annotating the students array list with @ManyToMany. The many-to-many annotation indicates the many-to-many relationship between the students and courses which means that one student can enroll in multiple courses and a single course will also contain a group of students registered for it.
Example 2:
Java
@Entity
public class Author {
@Id
@GeneratedValue
private long id;
private String name;
@ManyToMany
private ArrayList<Book> books;
}
@Entity
public class Book {
@Id
@GeneratedValue
private long id;
private String name;
private int pageCount;
@ManyToMany
private ArrayList<Author> authors;
}
|
Code Explanation:
In the above example, we are creating two entities for Book and an entity for the Author. The Book entity has several fields such as id, name, and the array list of books that are written by the current author. Similarly, we are creating an entity for Book in which we are creating different fields such as id, name, page count, and the array of authors. We are adding a @ManyToMany annotation for the array of authors which indicates that many authors can write one book as well as a book may contain multiple authors present in it. The @ManyToMany annotation indicates the many-to-many relationship between authors and books.
Share your thoughts in the comments
Please Login to comment...