Hibernate @ManyToMany - Bidirectional

We can create a Many to Many relationship between Persistent classes using @ManyToMany annotation.

Let us create a persistent class Student and Course as shown below. A Course can have many Students and a Student can take many courses. This creates a Many to Many relationship.

The following example shows a Bidirectional Many to Many mapping in Hibernate.

@Entity
@Table(name = "Student")
class Student
{
    @Id
    @Column(name="stu_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name="stu_name")
    private String name;

    @ManyToMany(mappedBy="students")
    private Set<Course> courses;
    // Getters and Setters
}

@Entity
@Table(name="Course")
class Course
{
    @Id
    @Column(name="course_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name="course_name")
    private String name;

    @ManyToMany(targetEntity=Student.class, cascade={CascadeType.ALL})
    @JoinTable(name="STUDENT_COURSES", 
            joinColumns=   { @JoinColumn(name="course_id") },
            inverseJoinColumns= { @JoinColumn(name="stu_id")} )
    private Set<Student> students;

    // Getter and Setters.
}

Previous: @ManyToMany - Unidirectional | Next: @ManyToMany - Extra Column

<
>