Hibernate @ManyToMany - Extra Column

We can create a Many to Many relationship between Persistent classes for an extra column by creating a third entity and then using OneToMany mapping between the two primary entities and the third joining entity.

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 with Extra Column in Hibernate.

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

    @Column("student_name")
    private String name;

    @OneToMany(mappedBy="student")
    private Set<StudentCourse> studentCourses;
}

@Entity
@Table(name="StudentCourse")
class StudentCourse
{
    @Id
    @GeneratedValue(GenerationStrategy.NATIVE)
    private Long id;

    @ManyToOne
    @JoinColumn("stu_id")
    private Student student;

    @ManyToOne
    @JoinColumn("course_id")
    private Course course;
}

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

    @Column("course_name")
    private String name;

    @OneToMany(mappedBy="course")
    private Set<StudentCourse> studentCourses;

}

Previous: @ManyToMany Bidirectional
<