The relationship maintenance between tables in Hibernate is the most important, and this is inseparable from cascade and inverse.
Table structure: Students and courses are many-to-many relationships, and the third table maps the relationships among the newcomers.
Class Structure:
Here to save some data:
@Testpublic void Save () {Session session = Factory.opensession (); Session.gettransaction (). Begin (); Course Course = new Course (); Course.setcname ("mathematics"); Course course1 = new Course (); Course1.setcname ("language"); Student stu = new Student (); Stu.setsname ("Zhang San"); Student stu1 = new Student () Stu1.setsname ("John Doe");//In code is course maintain the relationship between the two, so you need to set the corresponding map file inverse to False, if set to True , it causes the third table to be empty course.getstu (). Add (Stu); Course.getstu (). Add (STU1);//Because it is course to establish a relationship, the code is saved course, However, the cascade in the corresponding mapping file is set to all, so the student is saved while saving the course, and if you do not do this, you will get an error because the student class will not save
If the relationship is course, and the code is saved student is not saved course, because cascading is the relationship between the two will play a role session.save (course); Session.save (COURSE1); Session.gettransaction (). commit (); Session.close ();}
The corresponding mapping file is as follows:
<set name= "Stu" table= "Course_stu" cascade= "All" inverse= "true" > <key> <column name= "CID" ></column> </key> <many-to-many class= "Student" column= "Sid" ></many-to-many> </set>
"One-to-many is more than a party to maintain relationships, many to Dozzong on the page of the real side of the maintenance relationship"
Cascade and Inverse in hibernate