[Add to favorites] detailed description on Inverse and cascade ing of hibernate Sets

Source: Internet
Author: User

1. Where can I use cascade = "..."?

The cascade attribute is not required for many-to-many relationships. With this attribute, we only make it easier to insert or delete the object, as long as we insert or delete the object at the cascade source, all cascade relationships are automatically inserted or deleted. To make cascade correct, unsaved-value is a very important attribute. Hibernate uses this attribute to determine whether an object should be saved or updated. If the Object ID is unsaved-value, it means that this object is not a persistence object and must be saved (insert ); if the ID is not unsaved-value, it indicates that this object is a persistence object (which already exists in the Database) and only needs to be updated. The saveorupdate method also uses this mechanism.

2. Where should I use inverse = "ture "?

The default inverse attribute is false, that is, the link is maintained at both ends of the link. This means that if there is a student, teacher and teacherstudent table, student and teacher have many-to-many relationships, which are represented by the teacherstudent table. So when will we insert or delete records in the teacherstudent table to maintain the relationship? When Hibernate is used, we will not perform operations on the teacherstudent table. The operation on teacherstudent is done by hibernate for us. Hibernate is to check who is specified in the HBM file to maintain the relationship. When "who" is inserted or deleted, it will perform operations on the relational table. The premise is that the object "who" already knows the link, that is, the object at the other end of the link has been set or added to the object "who. As mentioned above, the default value of inverse is false, which means that both ends of the link maintain the relationship. Any operation will be performed on the table. When inverse = "true" is used at one end of a link, such as the bag or set in student, it indicates that the link is maintained by a teacher ). That is to say, when student is inserted, the teacherstudent table is not operated, even if student already knows the relationship. The Link Table operation is performed only when teacher is inserted or deleted. Therefore, it is incorrect to use inverse = "true" at both ends of the link, so that no operation is performed on the Link Table. When both ends are inverse = "false" or the default value isCodeMaintenance of the link display is also incorrect, which may cause two relationships to be inserted in the Link Table.

In one-to-many relationships, inverse makes more sense. In many-to-many scenarios, the inverse = "true" has almost the same effect (in terms of efficiency ). However, in one-to-many scenarios, if one party needs to maintain the relationship, it will update every object associated with this "1" Object in "multiple" when "one" side is inserted or deleted. If you want to maintain a "multi" relationship, there will be no update operation, because the relationship is in the Multi-Party object, just insert or delete the Multi-Party object. Of course, we also need to traverse the changes in the operation repair relationship displayed for each object of the "multi" side to reflect in the DB. In any case, it makes the relationship maintained by the "multi" Party more intuitive.

3. What is the difference between cascade and inverse?

As you can understand, cascade defines the cascading relationship between objects at both ends of the relationship to the object, while inverse defines the cascading relationship between the relationship and the object.

ALL: Perform Association operations in all cases.
None: No association operation is performed in all cases. This is the default value.
Save-Update: perform join operations when you execute save/update/saveorupdate.
Delete: perform join operations when executing Delete.

All indicates save-update + Delete.
All-delete-orphan indicates that when an orphan node is generated in the object graph, the node is deleted from the database.
All is better understood. For example, all-delete-orphan:
The relationship between category and item is one-to-many, that is, the category class has a set type variable items.
For example, two items, Item1 and item2, are saved in items. If the relation is defined as all-delete-orphan
When an item is deleted in items (for example, Item1 is deleted using the remove () method), the deleted item class instance
Becomes an orphan node. When category. Update () or session. Flush () is executed
Hibernate synchronizes cache and database, and deletes the records corresponding to Item1 in the database

4. How does hibernate update databases based on pojo?
4.0 hibernate will not perform mysterious processing on pojo objects before commit/flush.
4.0.1 when pojo is queried in the SELECT statement, Hibernate uses the field value to fill the attributes of pojo Based on the ing of "field -- attribute;
Then, an SQL statement is generated based on the link tag to query the relationpojo that meets the condition from the relationtable, And the relatinpojo
Put it in "link property. This process is mechanical.
4.0.2 after the pojo object is found, it will be a common Java object before commit (or flush), and hibernate will not do any extra work.
For example, you are not limited to setting a property value to null or any other value.
During the add (object) Operation of the Set class, the object value is not changed, and whether the parameter object is a pojo object is not checked.
Set the value of a "bridge property" of mainpojo. The value of the corresponding "bridge property" of relationpojo is not automatically set.
When session. Delete (pojo) is executed, the pojo itself does not change, and its attribute value does not change.
When session. Save (pojo) is executed, if the pojo ID is not generated by hibernate or the database, its value remains unchanged.
If the pojo ID is generated by hibernate or the database, Hibernate sets the ID to pojo.
Extend: For a set with lazy = true, when hibernate performs the set operation (calling the method declared in Java. util. Set ),
Will first inialize this set, that's all. Inialize only fetches set data from the database.
If a set has been inialize, the operation on it is the semantics defined in the Java. util. Set interface.
In addition, if the ID is generated by hibernate, Hibernate will change the pojo and set its ID when saving (pojo ).
The hashcode of the pojo may be changed. For details, see the post"
Some attributes marked in the mapping file and the operations on the pojo object will have an impact on database operations. These effects will only take effect at commit.
The pojo status before commit is not affected.
However, at the time of commit, it will be completely controlled by hibernate. It seems that it knows all the changes in the pojo object from creation to commit.
4.03. Associate update
The property corresponding to "link tag" is a pojo or a pojo set. Modifying the value of "link attribute" may update the maintable table or the relationtable table.
This type of update is currently called "associated Update ".

4.1.the role of the inverse attribute (assuming that the cascade attribute is not set)
4.1.1 "only set/MAP/LIST/array/bag has the inverse attribute ".
---- Take the mark set as an example. Specifically, it is "school Table of an address table" -- address. schoolset.
4.1.2 "the inverse attribute of the set determines whether the changes to the set are reflected in the database.
Inverse = false ---- reflect; inverse = true ---- do not reflect"
The default inverse attribute is false.
Applicable to the <one-to-operate> and <allow-to-operate> subtags.
4.1.2 is applicable to any set operation.
4.1.3 When inverse = false, how does hibernate reflect changes to the set to the database:
The operations on set mainly include: (1) adding the element address. getschoolset (). Add (oneschool );
(2) Delete the element address. getschoolset (). Remove (oneschool );
(3) Delete set address. setschoolset (null );
(4) set the new set address. setschoolset (newschoolset );
(5) transfer set otherschoolset = otheraddress. getschoolset ();
Otheraddress. setschoolset (null );
Address. setschoolset (otherschoolset );
(6) Changing the attribute value of the element in the set. If the key attribute is changed, this will cause an exception.
If the changes are common attributes, Hibernate considers that the set has not changed (the reason can be seen later ).
Therefore, this situation is not considered.
After the set is changed, Hibernate's operations on the database vary depending on the <one-to-operate> relationship or <allow-to-operate> relationship.
Changes to One-to-school and school set will change the data in the school Table:
# School_id is the primary key of the school table, and school_address is the address bar of the school table.
# The foreign key of the table school is school_address, which corresponds to the primary key address_id of the table address
(11) insert oneschool ---- sqlinsertrowstring:
Update school set school_address =? Where school_id =?
(Only update the value of foreign-key .)
(22) delete oneschool ---- sqldeleterowstring:
Update school set school_address = NULL where school_id =?
(It is strange to set foreign-Key to null. I don't know what the actual meaning is ?)
(33) delete belongs to all schools ---- sqldeletestring of an address:
Update school set school_address = NULL where school_address =?
(44) Update ---- sqlupdaterowstring: "", no need
Changes to school set will change the data in the address_school relational table:
# The relationship between "region-school" and "many to many" is a little far-fetched, just to make it easier to compare with the one-to-many relationship above.
# Assume that there is a relational table address_school, which has two fields address_id, school_id,
# These two fields correspond to the keys of the address and school tables respectively.
(11) insert SQL statement: insert into address_school (address_id, school_id)
Values (?,?)
(22) The delete SQL statement is: delete from address_school.
Where address_id =? And school_id =?
(33) The SQL statement for delete all is: delete from address_school
Where address_id =?
(44) The update SQL statement is ---- sqlupdaterowstring:
Update address_school set address_id =?
Where address_id =? And school_id =?
For the set operation (1), Hibernate will execute (11) sqlinsertrowstring
For the set operation (2), Hibernate will execute (22) sqldeleterowstring
For the set operation (3), Hibernate will execute (33) sqldeletestring
For the set operation (4), the old schoolset is deleted because it does not have the address to which it belongs, that is, the system first executes (33) sqldeletestring
Then add a new schoolset, that is, execute sqlinsertrowstring
The operation on set (5) actually transfers the set from one pojo to another:
Run sqldeletestring to delete the school to which the otheraddress belongs.
Then, run sqldeletestring to delete the original school address.
Finally, execute sqlinsertrowstring to add the otherschoolset to the address
Conclusion: (1) for one-to-minus, changing set will allow hibernate to execute a series of update statements without deleting/inserting data.
(2) For sequence-to-sequence, changing set only modifies the data in the relational table does not affect the other side of sequence-to-sequence.
(3) Although one-to-one operation and one-to-one operation are different, the objective is to maintain data consistency. All executed SQL statements
Only the "bridge field" is involved, and other fields are not considered or changed. Therefore, the operation on set (6) is ineffective.
Extend: For list, the index field may be maintained.
4.1.4 "inverse and cascade have nothing to do with each other ."
After commit, the two attributes have different timing. hibernate will set the cascade Attribute Based on changes to the pojo object,
Generates a series of actions, such as updateaction, deleteaction, and insertaction. Each action has an execute method to execute the corresponding SQL statement.
After all these actions are generated, Hibernate executes them together. Before executing the SQL statement, the inverse attribute takes effect,
If inverse is set to true, SQL is not executed. If inverse is set to false, SQL is executed.
4.1.5 The default value of inverse is false. Therefore, the inverse attribute is updated by default ".
4.1.6 suggestion: Set inverse = false only for set + upload-to-consume. Other tags do not consider the inverse attribute.
If the inverse attribute is not set, the default value of inverse is false.
4.2. Role of cascade attributes:
4.2.1 The cascade attribute is available only for "link tag": Allow-to-one, one-to-one, any,
Set (MAP, bag, idbag, list, array) + One-to-pair (bytes-to-Pair)
4.2.2 cascade refers to whether the associated object (passive party) performs the same operation simultaneously when the primary prosecution executes the operation.
The relationship between pojo and its link property is the relationship between the "Master Control-passive side". If the link property is a set, the passive side is one element in the set ,.
For example, a school has three attributes: region, principal, and student. The element is student)
When session. Delete (school) is executed, cascade determines whether to execute session. Delete (address), session. Delete (themaster ),
Whether to execute session. Delete (astudent) for each astudent ).
Extend: This is different from the inverse attribute. See section 4.3.
4.2.3 a cascade operation may trigger multiple associated operations. The previous operation is called "Master operation", and the next operation is called "associated operation ".
Optional value of the cascade attribute:
ALL: Perform Association operations in all cases.
None: No association operation is performed in all cases. This is the default value.
Save-Update: perform join operations when you execute save/update/saveorupdate.
Delete: perform join operations when executing Delete.
The specific "associated operation" is based on the "Master operation:
"Master operation" and "associated operation"
Session. saveorupdate --> session. saveorupdate (execute saveorupdate to actually execute save or update)
Session. Save ----> session. saveorupdate
Session. udpate --> session. saveorupdate
Session. Delete --> session. Delete
4.2.4 the sequence of the master and associated operations is "save one first, then save the snapshot; Delete the snapshot first, then delete one; update the master prosecution first, and then update the passive party"
For one-to-one, when its attribute constrained = "false" (default), it can be considered as a one-to-one relationship;
When its attribute constrained = "true", it can be seen as a forward-to-one relationship;
For role-to-role, it can be considered as one-to--role.
For example, a school has three attributes: Region (address), Principal (themaster, whose constrained = "false"), and student (set, whose element is student)
When session. Save (school) is executed,
The actual execution order is: Session. Save (Address );
Session. Save (school );
Session. Save (themaster );
For (for every student ){
Session. Save (astudent );
}
When session. Delete (school) is executed,
The actual execution sequence is: Session. Delete (themaster );
For (for every student ){
Session. Delete (astudent );
}
Session. Delete (school );
Session. Delete (Address );
When session. Update (school) is executed,
The actual execution sequence is: Session. Update (school );
Session. saveorupdate (Address );
Session. saveorupdate (themaster );
For (for every student ){
Session. saveorupdate (astudent );
}
Note: The Association operation caused by cascade operations is the saveorupdate operation, rather than the update operation.
The difference between saveorupdate and update is that the former decides whether to execute update or save based on whether the operation object is saved or not saved.
Extends: In reality, deleting a school will not delete the region, that is, the cascade of the region is generally set to false.
In addition, cascade = true is rarely set for the sequence-to-sequence relationship, but inverse = false. This reflects the differences between cascade and inverse. See 4.3
4.2.5 The default value of cascade is false. Therefore, the inverse attribute is updated by default ".
4.2.6 conclusion: cascade also performs this operation on its attributes (its cascade = true) when an object is operated.

4.3 comparison between inverse and cascade
These two attributes do not affect each other, but they have a similar effect, which can lead to updates to the relational table.
4.3.1 inverse is only valid for set + One-to-minus (or transfer-to-minus) and is invalid for allow-to-one and one-to-one.
Cascade is valid for all link tags.
4.3.1 inverse takes effect on the whole set object. Cascade takes effect on one element of the Set object. If the set is empty, cascade will not trigger association operations.
For example, set the set object to null, school. setstudentset (null)
Inverse causes hibernate to execute: udpate student set school_id = NULL where school_id =?
Cascade does not perform join update on the student table because there are no elements in the set.
Add another school, session. Save (school)
Inverse causes hibernate to execute:
For (for every student in school ){
Udpate student set school_id =? Where student_id =? // Change the student's school_id to the new school ID
}
Cascade causes hibernate to execute:
For (for every student in school ){
Session. Save (astudent); // execute the save operation on the student
}
Extends: If you change some elements in a set (for example, adding an element ),
Inverse: hibernate first checks which elements have changed and executes corresponding SQL statements on the changed elements.
Cascade: It always performs join operations on each element in the set.
(In the associated operation, Hibernate will determine whether the object to be operated has changed)
4.3.2 the two functions have different timing:
Cascade.
Inverse: During flush (commit will automatically execute flush). For all sets in the session, Hibernate checks whether each set has changed,
If (inverse = true) return;
We can see that cascade is first, and inverse is later.
4.3.3 inverse has different effects on set + One-to-sequence and set + sequence-to-sequence. The SQL statements generated by hibernate are different.
Execute the update Statement on the database tables of one-to-one and hibernate administrators.
For external-to-relational, Hibernate executes the insert/update/delte Statement on the relational table. Note that it is not a relational table but a relational table on the relational table.
Cascase is consistent with set, regardless of one-to-least or minus-to-least. The operation is passed to every element in the set. So it always updates the lifecycle
Database table.
4.3.4 suggestion: Set inverse = false only for set + failed-to-Disable. For other tags, set inverse = true without considering the inverse attribute.
For cascade, cascade deletion is not set for one-to-one, including replicate-to-pair, and constrained = true.

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.