Hibernate @ManyToMany - Unidirectional
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
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 unidirectional 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;
// 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.
}