I. Overview
Many-to-many association relationships can be implemented in Java objects by defining collection types. In the relational data model, it is not possible to directly express many-to-many association relationships between tables and tables, but rather to create an intermediate table that contains both sides of the primary key to express the many-to-many association relationships between the two tables.
Example: We use an example of student and course (students and courses) to demonstrate a many-to-many association relationship.
(1) Creating student and course classes
public class Student { private Integer ID; private String name; Use a collection that contains the course object selected by the student private set<course> courses=new hashset<course> (); Public Integer getId () { return ID; } public void SetId (Integer id) { this.id = ID; } Public String GetName () { return name; } public void SetName (String name) { this.name = name; } Public set<course> getcourses () { return courses; } public void setcourses (set<course> courses) { this.courses = courses; } }
public class Course {private Integer ID; private String name; Use a collection to include all students who choose the course private set<student> students=new hashset<student> (); Public Integer GetId () {return id; } public void SetId (Integer id) {this.id = ID; } public String GetName () {return name; } public void SetName (String name) {this.name = name; } public set<student> getstudents () {return students; } public void Setstudents (set<student> students) {this.students = Studen Ts } }
(2) Write our mapping file
Test:
public class Demo {@Test public void fun () {//Read config file Configuration Conf=new configuration (). Configure (); Create Factory Sessionfactory Sessionfactory=conf.buildsessionfactory () based on configuration; Session session = Sessionfactory.opensession (); Transaction ts=session.begintransaction (); Creation of two Student Student s1=new Student (); S1.setname ("Tom"); Student s2=new Student (); S2.setname ("Jack"); Creation of three Course Course c1=new Course (); C1.setname ("language"); Course c2=new Course (); C2.setname ("mathematics"); Course c3=new Course (); C3.setname ("English"); Because the association relationship is maintained by student, no courses are required to correlate student s1.getcourses (). Add(C1); S1.getcourses (). Add (C2); S1.getcourses (). Add (C3); S2.getcourses (). Add (C1); S2.getcourses (). Add (C2); S2.getcourses (). Add (C3); Because the Cascade save is set, only save student can Session.save (S1); Session.save (S2); Ts.commit (); Session.close (); Sessionfactory.close (); }} results, three tables were generated in the database. Student and course, and the data in the intermediate table Student_course, correspond to each other.
(ix) Many-to-many association relationships in hibernate