Cascade and Inverse in hibernate

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.