In many to many, it creates three tables in total.
Student,teacher,student_teacher
In we example, all mappings is done in teacher class
1.Annotation
Teacher:
We create @ManyToMany @JoinTable (name= "xx", @JoinColumns ={@JoinColumn ()}, @inverseJoinColumns ={@JoinColumn ()})
@JoinColumns links its PK to the junction table
Why is we using @JoinColumns not @JoinColumn directly?
B/C we could has composite primary keys, thus, we should use @JoinColumns;
@inverseJoinColumns Links second table ' s PK to the junction table
@Entity Public classTeacher {PrivateString name; Private intID; PrivateSet<student>students; @ManyToMany @JoinTable (Name= "t_s", //join column points to this.id;joincolumns={@JoinColumn (name= "teacher_id")}, //Inversejoincolumns points to ID of student classinversejoincolumns={@JoinColumn (name= "stu_id")} ) PublicSet<student>getstudents () {returnstudents; } Public voidSetstudents (set<student>students) { This. Students =students; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } @Id Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; }} @Entity @table (name= "T_student") Public classStudent {Private intAge ; Private intClassID; PrivateString name; Private intID;
Public intGetClassID () {returnClassID; } Public voidSetclassid (intClassID) { This. ClassID =ClassID; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } @Id Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; }}
2.XML
Teacher class:
<Key> appears anywhere the parent mapping element defines a join to a new table that references the primary Key of T He original table. It also defines the foreign key in the joined table
<key column= "XX" > XX is the ID of This.class;
<many-to-many class= "Student" column= "XX" > XX is the ID of student class
Package= "Com.hibernate.model" ><className= "Teacher" table= "T_teacher" > <id name= "id" ></id> <property name= "name" ></property> <!--table= "xx" xx is name of junction table--<set name= "Students" table= "Tea_stu" > <key column = "teacher_id" ></key> <many-to-manyclass= "Com.hibernate.model.Student" column= "stu_id"/> </set></class> Package= "Com.hibernate.model" ><className= "Student" table = "S_student" > <id name= "id" ></id> <property name= "name" ></property> <property name= "Age" ></property> <property name= "ClassID" ></property></class>
Hibernate Many-to-many Unidirectional Mapping