A detailed explanation of cascade attribute and inverse attribute concept in hibernate

Source: Internet
Author: User
Tags set set
In the process of learning hibernate, the concept of cascade attributes and inverse attributes has been blurred, and many beginners may encounter similar situations, mainly with the following problems:

1, Cascade Properties and the role of inverse properties, that is, why use them.

2, under what circumstances to use them.

3, how to use them.

For the configuration of Hibernate entity objects, they may often be used, so it must be clearly understood,

So I find information on the Internet and write examples of a large number of tests to solve the problem.

Comparison of Inverse and cascade

The two properties do not affect each other, but are somewhat similar in nature, which can trigger updates to the relational table.


Inverse:

When mapping a one-to-many relationship, set to False (default false), one party maintains the relationship between the two, and when set to true, one party does not maintain the relationship between the two. Four-word generalization--association update.

function: When you do not use it (that is, the default false), on one side of the data operation (add, update, delete), if you change the set set, in order to maintain the relationship with more than one side, Hibernate will add an additional UPDATE statement , Updating multiple side-associated fields reduces execution efficiency and consumes additional performance.

Inverse=true's role is: no matter how one side of the data operation, will not be reflected to the other side, does not trigger the corresponding update operation.

Configuration scope: can only be configured on the One-to-many,many-to-many set label , a one-to-many hit one side. Example 1:when One-to-many.

The relationship between students (Student) and the Class (ClassInfo), one of the students, the other side of the class

The class mapping file ClassInfo.hbm.xml is configured as follows (by default):

<set name= "Students" >
    <key column= "classId"/> <one-to-many class=
    "Student"/>
</ Set>
Code for insert operation:

		Student Student = new Student ();
		Student.setname ("John");
			
		ClassInfo ClassInfo = new ClassInfo ();
	    Classinfo.setname ("key Class");

	    Classinfo.getstudents (). Add (student);  This line of code indicates that one side of the class controls the operation of
	    Session.save (student);
	    Session.save (ClassInfo);

To generate an SQL statement:

Hibernate: 
    insert 
    into
        tb_student
        (name, Cardid, classId, id) 
    values
        (?,?,?,?)
Hibernate: 
    insert 
    into
        tb_classinfo
        (name, id) 
    values
        (?,?)
Hibernate: 
    update
        tb_student 
    set
        classid=? 
    where
        id=?
This shows that each additional student generates an UPDATE statement.

The data in the database are as follows:

Tb_classinfo:id Name

1 Key Classes

Tb_student:id name ClassId

1 Sheets 31

If you configure the ClassInfo.hbm.xml as follows, the rest will not change:

< set inverse to True-->
<set name= "Students" inverse= "true" >
    <key column= "ClassId"/>
    <one-to-many class= "Student"/>
</set>
After performing the same insert operation,

To generate an SQL statement:

Hibernate: 
    insert 
    into
        tb_student
        (name, Cardid, classId, id) 
    values
        (?,?,?,?)
Hibernate: 
    insert 
    into
        tb_classinfo
        (name, id) 
    values
        (?,?)
Visible, there is no UPDATE statement.

The data in the database are as follows:

Tb_classinfo:id Name

1 Key Classes

Tb_student:id name ClassId

1 sheets of three null

The field ClassID in table tb_student is empty, indicating the insertion of the class, and not maintaining the relationship with the student that corresponds to it.
Example 2:when Many-to-many.

Students (Student) and courses (Course), many-to-many relationships

The many-to-many relationship is that both will maintain a middle table, Tb_student_course,

At this point, the student table and schedule are a one-to-many relationship to the middle table.

The Student.hbm.xml configuration is as follows:

        <set name= "Courses" table= "Tb_student_course" >
		<key column= "StudentID"/>
		<many-to-many class= "Course" column= "CourseID"/>
	</set>
Code for insert operation:

	Student Student = new Student ();
	Student.setname ("Dick");
		
	Course Course = new Course ();
	Course.setname ("foreign Language");
		
	Student.getcourses (). Add (course); By the student main control inserts the Operation
		
	Session.save (course);
	Session.save (student);
To generate an SQL statement:
Hibernate: 
    insert 
    into
        tb_course
        (name, id) 
    values
        (?,?)
Hibernate: 
    insert 
    into
        tb_student
        (name, Cardid, classId, id) 
    values
        (?,?,?,?)
Hibernate: 
    insert 
    into
        tb_student_course
        (StudentID, CourseID) 
    values
        (?,?)
This shows: Each additional student and course information, after the insert Student information and course information into the database,

They also insert data into the intermediate table Tb_student_course they maintain, which is to maintain their relationships.

The data in the database are as follows:

Tb_student:id Name

1 dick

Tb_course:id Name

1 Foreign languages

Tb_student_course:studentid CourseID

1 1

If you modify the Student.hbm.xml configuration as follows, the rest will not change:

        <!--set Inverse to True--> <set name= "courses" table= "Tb_student_course"
        inverse= "true" >
		<key column= "StudentID"/>
		<many-to-many class= "Course" column= "CourseID"/>
	</set>

After performing the same insert operation,

To generate an SQL statement:

Hibernate: 
    insert 
    into
        tb_course
        (name, id) 
    values
        (?,?)
Hibernate: 
    insert 
    into
        tb_student
        (name, Cardid, classId, id) 
    values
        (?,?,?,?)
Visible, only two INSERT statements.

The data in the database are as follows:

Tb_student:id Name

1 dick

Tb_course:id Name

1 Foreign languages

Tb_student_course:studentid CourseID

                                          This table has no data

It can be concluded that for data insertion operations, inverse decides whether to reflect changes to the set to the database, that is, whether an UPDATE statement is generated. One-to-many, for data update and delete operations, as well as the insertion of data (this is not specifically demonstrated), when Inverse=false (by default), changes to the set set will generate an UPDATE statement to update the corresponding multiple side of the data. When inverse=true, changes to the set set do not produce an UPDATE statement that updates the data of the corresponding multiple party. Waiver of the right to maintain the relationship between the two.
Many-to-many, in fact, can also be seen as a special form of one-to-many, student and course jointly maintain an intermediate table tb_student_course. Student table or Course table for the middle Tb_student_course, is a one-to-many relationship, so whether it is student or course, change set, only update the data in the middle table, will not affect the other side. Suggested that a one-to-many mapping configuration, generally do not allow one side of the maintenance relationship, will be lost performance, so that more side to maintain. So one side of the configuration attribute inverse=true. But when more than a lot of circumstances, must let inverse=false.

Delete operation Example:

Delete a class.
	/////Inverse=false, the Student table ClassID field is not updated when the foreign key classid of the associated student table is set to null and the class
	//Inverse=true is deleted. Direct deletion of the class will be due to both the foreign key constraints, can not be deleted, reported an exception.
	ClassInfo ClassInfo = (ClassInfo) session.get (Classinfo.class, 1);		
	Session.delete (ClassInfo);


Cascade:

Cascade refers to whether the associated object (the passive side) performs the same operation synchronously when the master executes the action.

Action : The operation of an object that triggers the operation of all objects associated with it by cascading, simplifying the code.

Configuration scope: only "relational tags" have cascade attributes: Many-to-one,one-to-one, any, set (map, bag, idbag, list, array), One-to-many ( Many-to-many)

Suppose three objects: Student (student), ClassInfo (Class), Course (course)

Student (Multi)----------> ClassInfo (i)

Student (Multi)----------> Course (Multi)

When I perform the Save Student object operation:

Session.save (Student) Cascade decides whether to execute: save_or_update (ClassInfo), Save_or_update (course)

When I perform the update student object operation:

Session.update (Student) Cascade decides whether to execute: save_or_update (ClassInfo), Save_or_update (course)

When I perform the Delete student object operation:

Session.delete (Student) Cascade decides whether to execute: session.delete (ClassInfo), Session.delete (course)

Note: The active operation of the Save or update may be either save or update,hibernate, depending on whether the associated object already exists in the database or not, the decision is save or update.

Suggestion:Cascade, General to many-to-one,many-to-many,constrained=true one-to-one do not set cascading deletion

Under Many-to-many, Cascade affects the other side, and inverse affects the middle table.



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.