About Inverse=true and Cascade in Hibernate

Source: Internet
Author: User
Tags new set
About Inverse=true and Cascade in Hibernate
Hibernate set mapping inverse and cascade detailed
1, in the end where to use Cascade= "...".
Cascade attribute is not a many-to-many relationship must be used, with it just let us insert or delete to the image of more convenient, as long as the source of cascade inserted or deleted, all the cascade relationship will be automatically inserted or deleted. is to be able to correct the cascade,unsaved-value is a very important attribute. Hibernate this property to determine whether an object should be save or update, if the object's ID is unsaved-value, it means that the object is not persistence objects to save (insert) If the ID is unsaved-value, it means the object is persistence object (already exists in the database), as long as the update is OK. The Saveorupdate method is also used in this mechanism.

2, in the end where to use inverse= "Ture"?

The inverse property defaults to false, meaning that both ends of the relationship maintain the relationship. If there is a student, teacher and teacherstudent table, student and teacher are many-to-many relationships, this relationship is represented by the Teacherstudent table. So when do you want to insert or delete records in the Teacherstudent table to maintain the relationship? When using hibernate, we do not display the action on the Teacherstudent table. The operation of Teacherstudent is hibernate help us to do. Hibernate is the "who" maintenance relationship that is specified in the HBM file, and the action on the relational table is triggered when the "who" is inserted or deleted. The premise is that the "who" object already knows the relationship, meaning that the object at the other end of the relationship has been set or added to the "who" object. Previously said inverse default is false, that is, the relationship between the two sides of the maintenance relationship, any one of them will trigger the operation of the relational table. When inverse= "true" is used on the end of a relationship, such as a map or set in student, it means that the relationship is maintained by another (Teacher). This means that when this is inserted into the student, the Teacherstudent table is not manipulated, even if student already knows the relationship. Action on a relational table is triggered only when teacher is inserted or deleted. Therefore, when both ends of the relationship are inverse= "true", it causes no action to trigger the operation of the relational table. When both ends are inverse= "false" or a default value, the maintenance of the relationship displayed in the code is also incorrect, resulting in the insertion of a two-second relationship in the relational table.

Inverse is more meaningful in a one-to-many relationship. In Many-to-many, at which end inverse= the "true" effect is similar (in efficiency). But in One-to-many, if one party maintains a relationship, it makes it necessary to update the "many" side of each object that has a relationship to the "one" object when inserting or deleting "a" side. And if the "more" aspect of maintaining the relationship there will be no update operation, because the relationship is in the various objects, directly to insert or delete multiple objects on the line. Of course at this time also to traverse the "many" side of each object to show the changes in the operation of the repair relationship into the db. In any case, it is more intuitive to maintain the "many" side of the relationship.

3, cascade and inverse what is the difference.

It can be understood that Cascade defines a cascade relationship between two objects to an object, while inverse defines a relationship and a cascading relationship between objects.



All: Associated operations are performed in all cases.
None: No associated action is performed in all cases. This is the default value.
Save-update: Associate action when performing save/update/saveorupdate.
Delete: The associated action is performed when the delete is executed.
All means Save-update + DELETE
All-delete-orphan means that when an orphan node is generated in the object graph, the node is deleted in the database.
All better to understand, here is an example to illustrate All-delete-orphan:
Category is a One-to-many relationship with item, meaning that there is a set type of variable items in the Category class.
For example, there are two items in the item, ITEM1,ITEM2, if the definition of the relationship is All-delete-orphan, when the items delete an item (such as the Remove () method to delete the item1), Then the deleted item class instance becomes an orphan node, and when the Category.update (), or Session.flush () is executed, the hibernate synchronizes the cache and the database, deleting the corresponding records item1 the database

4. Hibernate how to update a database based on Pojo

4.0 before the Commit/flush, hibernate would not deal with the Pojo object mysteriously.
4.0.1 in the select query out of Pojo, hibernate according to the "field-attribute" of the corresponding relationship, with the value of the field to fill Pojo attributes;
The SQL statement is then generated from the relationtable to query the Relationpojo that satisfies the condition, and the Relatinpojo
In the relationship properties. This process is mechanical.

4.0.2 after the Pojo object is detected, it will be a normal Java object before the commit (or flush), and hibernate will not do any extra hands and feet.
For example, you don't have to restrict you to set the value of a property to null or any other value
The Add (object) operation of set class set does not change the value of object and does not check whether the parameter object is a Pojo object
Sets the value of a "bridge property" for Mainpojo, and does not automatically set the value of the corresponding "Bridge property" for Relationpojo.
When executing session.delete (Pojo), the Pojo itself does not change, nor does his property value change.
When executing session.save (POJO), its value does not change if the Pojo ID is not hibernate or database-generated.
If the ID of the Pojo is hibernate or the database is generated, then hibernate will set the ID to Pojo.

Extend: Lazy=true Set,hibernate is in the operation of the set (invoking the method declared in Java.util.Set)
Will inialize this set first, that's all. The inialize simply fished out the set's data from the database.
If a set has been inialize, then the operation on it is the semantics defined in the Java.util.Set interface.

In addition, if the ID is generated by hibernate, then at Save (Pojo), hibernate changes the Pojo and sets its ID, which
May change the Pojo of the hashcode, discussed in detail in the post ""

The operations of certain attributes and Pojo objects that are marked in the mapping file affect the database operation, and these effects occur at commit time.
The state of Pojo before a commit is not affected by them.

At the time of the commit, however, it will be fully controlled by hibernate, and it seems to know all the changes in the Pojo object from creation to commit.


4.01. Associate Update
The property corresponding to the relationship tag is a pojo or a Pojo collection, and modifying the value of the relationship property can cause an update to the Maintable table, or it may update the relationtable table.

This update is called "Association update".


The role of the 4.1.inverse property (assuming that the Cascade property is not set)
4.1.1 "only Collection tags (set/map/list/array/bag) have inverse attributes."
———— may wish to mark set as an example, specifically "a region (Address table) of the school (school table)"-Address.schoolset.

The inverse property of the 4.1.2 set determines whether changes to the set are reflected in the database.
Inverse=false ———— reflection; Inverse=true ———— does not reflect "
Inverse property defaults to False

Both of the <one-to-many> and <many-to-many> child tags apply.
Regardless of what you do with set, 4.1.2 applies.

4.1.3 when Inverse=false, hibernate how changes to the set are reflected in the database:

The operation of the set mainly includes: (1) add Element Address.getschoolset (). Add (Oneschool);
(2) Delete element Address.getschoolset (). Remove (Oneschool);
(3) Delete set address.setschoolset (null);
(4) Setting the new set Address.setschoolset (Newschoolset);
(5) Transfer Set otherschoolset = Otheraddress.getschoolset ();
Otheraddress.setschoolset (NULL);
Address.setschoolset (Otherschoolset);
(6) Changing the value of the attribute of the element in set if it is changing the key property, this can cause an exception
If you change the normal properties, hibernate that the set does not change (see the reason behind).
So this situation is not considered.

After the set is changed, the operation of the hibernate database is different according to the <one-to-many> relationship or <many-to-many> relationship.

For One-to-many, changes to the school set change the data in the table school:
#SCHOOL_ID是school表的主键, School_address is the Address field in the SCHOOL table
#表School的外键为SCHOOL_ADDRESS, it corresponds to the primary key of the table address address_id
(one) Insert Oneschool ———— sqlinsertrowstring:
Update SCHOOL set school_address=? where school_id=?
(Only the value of the update Foreign-key.) )
(a) Delete Oneschool ———— sqldeleterowstring:
Update SCHOOL set school_address=null where school_id=?
(Strangely, setting Foreign-key to null is not known to have any practical meaning.) )
(a) Delete all school ———— sqldeletestring belonging to an address:
Update SCHOOL set school_address=null where school_address=?
(a) Update ———— sqlupdaterowstring: "", no need

For Many-to-many, changes to the school set change the data in the relational table Address_school:
# The relationship between "regional ———— schools" is a bit far-fetched, just to make it easier to compare with the one-to-many above
#假设有一个关系表ADDRESS_SCHOOL, there are two fields address_id, school_id,
#这两个字段分别对应ADDRESS和SCHOOL两表的key
(one) Insert SQL statement: INSERT INTO Address_school (address_id, school_id)
VALUES (?,?)
The SQL statement for delete is: delete from Address_school
where address_id=? and school_id=?
The SQL statement for delete all is: Delete from Address_school
where address_id=?
The SQL statement for update is ———— sqlupdaterowstring:
Update Address_school set address_id=?
where address_id=? and school_id=?

Operation on set (1), Hibernate will execute (one) sqlinsertrowstring
Operation on set (2), Hibernate will perform () sqldeleterowstring
Operation on set (3), Hibernate will perform (sqldeletestring)
Operation on set (4), the old Schoolset because does not belong to address, so be all delete, namely first executes (the) sqldeletestring
Then add a new schoolset, that is, then execute the sqlinsertrowstring
The operation on set (5), in effect, is to transfer set from one Pojo to another pojo:
First, execute sqldeletestring, delete the school that otheraddress belongs to
Then, execute sqldeletestring, remove the original school
Finally, execute sqlinsertrowstring and add Otherschoolset to address

Summary: (1) for one-to-many, changing set allows Hibernate to execute a series of UPDATE statements that do not delete/insert data
(2) for Many-to-many, changing the set, modifying only the data of the relational table, does not affect the other side of the Many-to-many.
(3) Although One-to-many and Many-to-many database operations are not the same, but the purpose is one: maintain data consistency. The executed SQL is
Only refers to the "bridge field", does not consider or change other fields, so the operation of the set (6) is not effective.
Extend: For list, the index field may also be maintained.

4.1.4 "Inverse and cascade have nothing to do with each other, without any involvement. ”
After a commit, the two properties work differently, hibernate based on changes to the Pojo object, and the Cascade property settings,
Generates a series of action, such as Updateaction,deleteaction,insertaction, and each action has an Execute method to execute the corresponding SQL statement.
After all of these action is generated, hibernate executes them together, and the inverse property works before executing SQL.
When inverse=true, SQL is not executed, and SQL is executed when inverse=false.

The default value for the 4.1.5 inverse is false, so the inverse property defaults to "Associate update."

4.1.6 recommends that you set the Inverse=false only on set + Many-to-many, and that the other tags do not consider the inverse attribute.
Unfortunately, inverse defaults to False when the inverse property is not set.

4.2. The role of the Cascade (Cascade) attribute:
4.2.1 Only "relationship markers" have cascade attributes: Many-to-one,one-to-one, any,
Set (map, bag, idbag, list, array) + One-to-many (many-to-many)

4.2. Level 2 refers to whether the associated object (the passive side) performs the same operation synchronously when the master executes the action.
The relationship between Pojo and its property is the relationship between the "host" and the passive side, and if the relation attribute is a set, then the passive side is an element of the set.
For example: the school (School) has three attributes: region (address), Principal (Themaster) and student (Set, element Student)
When executing session.delete (school), the cascade determines whether to execute Session.delete (address), Session.delete (Themaster),
Whether to perform session.delete (astudent) for each astudent.

Extend: There is a difference between this and the inverse attribute. See 4.3.

4.2.31 Operations may trigger multiple association operations because of cascading cascade. The previous operation is called "Master Operation", and the latter is called "associated operation".
Optional value for the Cascade property:
All: Associated operations are performed in all cases.
None: No associated action is performed in all cases. This is the default value.
Save-update: Associate action when performing save/update/saveorupdate.
Delete: The associated action is performed when the delete is executed.

What "Association actions" to perform specifically are based on the master action:
"Master action" "Associated action"
Session.saveorupdate--> session.saveorupdate (execution saveorupdate actually performs save or update)
Session.save----> Session.saveorupdate
Session.udpate--> Session.saveorupdate
Session.delete--> Session.delete

4.2.4 Master operation and associated operation order is "first save one, then save many, first delete the many, then delete one; update the main control, then update the passive side"
For one-to-one, when its property constrained= "false" (the default), it can be viewed as a one-to-many relationship;
When its attribute constrained= "true", it can be regarded as a many-to-one relation;
For Many-to-many, it can be regarded as one-to-many.

For example: the school (School) has three attributes: the region (address), the principal (Themaster, its constrained= "false") and the student (Set, element is student)
When the Session.save (school) is executed,
The actual order of execution is: Session.save (address);
Session.save (school);
Session.save (Themaster);
For (to each student) {
Session.save (astudent);
}

When the Session.delete (school) is executed,
The actual order of execution is: Session.delete (themaster);
For (to each student) {
Session.delete (astudent);
}
Session.delete (school);
Session.delete (address);

When the Session.update (school) is executed,
The actual order of execution is: Session.update (school);
Session.saveorupdate (address);
Session.saveorupdate (Themaster);
For (to each student) {
Session.saveorupdate (astudent);
}
Note: The update operation is a saveorupdate operation, not an update operation, because the associated operation is raised by cascading.
The difference between saveorupdate and update is whether the former determines whether to execute update or save, depending on whether the action object is saved or not saved

Extends: In practice, deleting a school does not delete the area, that is, the region's cascade is generally set to False
In addition, the many-to-many relationship rarely sets the cascade=true, but sets the Inverse=false. This reflects the difference between cascade and inverse. See 4.3

The default value for the 4.2.6 cascade is false, so the inverse property defaults to "Associate update."

4.2.7 Summary: Cascading (Cascade) is the operation of an object, as well as its properties (its cascade=true).


Comparison of 4.3 inverse and cascade
The two properties do not affect each other, but are somewhat similar in nature, triggering updates to the relational table.

4.3.1 Inverse is valid only for Set+one-to-many (or Many-to-many), Many-to-one, one-to-one invalid.
Cascade is valid for relation tags.

4.3.2 Inverse works on the aggregate object as a whole, cascade works on one element of the collection object, and if the collection is empty, then Cascade does not raise an associated action.
For example, set the collection object to null, School.setstudentset (NULL)
Inverse causes hibernate execution: udpate STUDENT set school_id=null where school_id=?
Cascade does not perform an associated update to the student table because there are no elements in the collection.

More than a new school, Session.save (school)
Inverse leads to hibernate execution:
for (to (school each student) {
Udpate STUDENT set school_id=? where student_id=? Change the student's school_id to the new school ID
}
Cascade leads to hibernate execution:
For (every student of school) {
Session.save (astudent); Perform a save operation on a student
}

Extends: If you change some of the elements in a collection (such as adding an element),
Inverse:hibernate first to determine which elements have changed, and to execute the corresponding SQL for the changed elements
Cascade: It always performs associated operations on each element in the collection.
(In an associated operation, hibernate determines whether the object of the action changes)

4.3. The timing of the 22 functions is different:
Cascade: Cascade occurs when the control is operated on.
Inverse: When flush (commit automatically executes flush), determine if each set has changed for all set,hibernate in the session.
Execute the corresponding SQL for the changed set, before executing, there will be a judgment: if (inverse = = true) return;

Can see cascade first, inverse in after.

The 4.3.3 inverse has different effects on set + One-to-many and set + Many-to-many. Hibernate generated SQL is different.
Executes an UPDATE statement on the database table of the one-to-many,hibernate against the many side.
For Many-to-many, Hibernate executes the Insert/update/delte statement on the relational table, noting that it is not a database table for the many side but a relational table.

Cascase is consistent with set, regardless of one-to-many or many-to-many. All simply pass the operation to each element in the set. So it always updates many
Side of the database table.

4.3.4 recommends that you set the Inverse=false only for set + Many-to-many, and that the other tags do not consider the inverse attribute and are set to Inverse=true.

For Cascade, General Many-to-one,many-to-many,constrained=true one-to-one do not set cascade deletion

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.