Hibernate collection mapping Inverse and cascade

Source: Internet
Author: User
Tags new set

1, exactly where to use cascade= "..."?

Cascade property is not a many-to-many relationship must be used, with it just let us in the insertion or deletion of the image is more convenient, as long as the cascade at the source of the insertion or deletion, all cascade relationship will be inserted or deleted by themselves. is to be able to correct cascade,unsaved-value is a very important attribute. Hibernate uses this property to determine whether an object should be save or update, and if the object's ID is unsaved-value, it means that the object is not persistence objects to save (insert) If the ID is a non-unsaved-value, it means that the object is persistence objects (which already exist in the database), as long as the update is done. The Saveorupdate method is also used for this mechanism.

2, exactly where to use inverse= "Ture"?

The

inverse property is false by default, meaning that both sides of the relationship maintain relationships. This means that if there is a student, teacher and teacherstudent tables, student and teacher are many-to-many-to-many relationships, the relationship is represented by the Teacherstudent table. So when do you insert or delete records from the Teacherstudent table to maintain relationships? When using hibernate, we do not display the Teacherstudent table to do the operation. The operation of the teacherstudent is what hibernate did for us. Hibernate is to look at the hbm file that specifies "who" maintains the relationship, which, when inserting or deleting "who", sends the action to the relational table. The premise is that the "who" object already knows the relationship, which means that the object of the other end is set or add to the "who" object. As I said earlier, inverse defaults to false, which means that the relationship is maintained at both ends, and any operation on the table will be made. When inverse= "true" is used in the end of a relationship, such as bag or set in student, it means that the relationship is maintained by another level (Teacher). This means that when this is inserted into the student, the Teacherstudent table is not manipulated, even if student already knows the relationship. Operations on a relational table are only sent when teacher is inserted or deleted. Therefore, it is not right to use inverse= "true" at both ends of the relationship, which causes any operation to be made without the action on the relational table. When both ends are inverse= "false" or the default value is, the maintenance of the Code on the relationship display is not correct, resulting in a two-time relationship being inserted into the relational table.

It is more meaningful to inverse in a one-to-many relationship. In many-to-many, on which side inverse= "true" effect is similar (in efficiency). However, in a one-to-many, if you want to maintain a relationship, you can insert or delete "a" side to update the "many" side of each object that has a relationship with the "one". And if the "many" aspects of the maintenance relationship will not have an update operation, because the relationship is in the object of the multi-party, directly into the insertion or deletion of multiple objects on the line. Of course at this time also to traverse the "many" side of each object display the changes in the operation of the relationship reflected in the DB. In any case, it is more intuitive to maintain the "many" side of the relationship.

3. What is the difference between cascade and inverse?

As you can understand, Cascade defines a cascade relationship between objects on both ends of the relationship, and inverse defines the relationship and the cascade of objects.

All: Associated operations are performed in all cases.
None: Associated operations are not performed in all cases. This is the default value.
Save-update: The associated operation is performed when Save/update/saveorupdate is executed.
Delete: The associated operation 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 is good to understand, for example, say 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, the current items store two item, ITEM1,ITEM2, if the relationship is defined as All-delete-orphan
When an item is deleted from items (such as removing item1 with the Remove () method), the deleted item class instance
will become an orphan node when executing category.update (), or Session.flush ()
Hibernate synchronizes the cache and the database, deleting the corresponding records in the database item1

//////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////

4. Hibernate how to update a database based on Pojo

4.0 before Commit/flush, Hibernate does not deal mysteriously with Pojo objects.
4.0.1 when the Select queries out Pojo, hibernate populates the Pojo property with the value of the field based on the corresponding relationship of the field-attribute;
The SQL statements generated from the relationtable are then queried for the relationpojo that satisfy the conditions, and these Relatinpojo
In the relationship properties. The 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 extra work.
For example, you do not have to limit the value of setting a property to null or any other value
When the Add (object) operation of the collection class set does not change the value of the object, it does not check whether the parameter object is a Pojo object
Setting the value of a "bridge property" for Mainpojo does not automatically set the value of the corresponding "Bridge property" for Relationpojo.
When executing session.delete (Pojo), the Pojo itself does not change and his property value does not change.
When you execute Session.save (Pojo), if the ID of Pojo is not hibernate or database generation, its value does not change.
If Pojo's ID is hibernate or database generation, Hibernate will set the ID to Pojo.

Extend: When the set,hibernate of Lazy=true is being set (invoking the method declared in Java.util.Set)
Will inialize this set first, that's all. Inialize simply removes set 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, hibernate changes the Pojo at Save (Pojo) and sets its ID, which
May change the Pojo of the hashcode, in detail to discuss the "

Some of the attributes tagged in the mapping file and the operations of the Pojo object have an impact on the database operation, all of which will be in effect at commit.
And the state of Pojo before commit is unaffected by them.

However, at the time of the commit, hibernate will be fully in control and it seems to know all the changes in the middle of the Pojo object from creation to commit.


4.01. Associated Updates
The attribute corresponding to the relationship token is a pojo or a Pojo collection, and modifying the value of the relationship property can cause the Maintable table to be updated or the Relationtable table to be updated.

This update is called "Associated updates".


The function of the 4.1.inverse attribute (assuming that the Cascade property is not set)
4.1.1 "Only the collection tag (set/map/list/array/bag) has the inverse attribute."
———— may wish to mark set as an example, specifically "a region (Address table) of the school (school table)"--address.schoolset.

4.1.2 "Set's Inverse property determines whether changes to the set are reflected in the database.
Inverse=false ———— reflection; Inverse=true ———— not reflected "
Inverse property defaults to False

Both of the <one-to-many> and <many-to-many> sub-tags apply.
Regardless of what the set does, 4.1.2 applies.

4.1.3 when Inverse=false, Hibernate is how to reflect the changes to the set in the database:

The operation of set is mainly: (1) add Element Address.getschoolset (). Add (Oneschool);
(2) Remove the element Address.getschoolset (). Remove (Oneschool);
(3) Delete set address.setschoolset (null);
(4) Set up a new set Address.setschoolset (Newschoolset);
(5) Transfer Set otherschoolset = Otheraddress.getschoolset ();
Otheraddress.setschoolset (NULL);
Address.setschoolset (Otherschoolset);
(6) Change the value of the attribute of the element in set if the key property is changed, this results in an exception
If you change the normal attribute, hibernate considers the set to be unchanged (see the reason behind it).
So this situation is not considered.

After changing the set, Hibernate's operation on the database is different depending on whether it is a <one-to-many> relationship or a <many-to-many> relationship.
For One-to-many, changes to the school set change the data in table school:
#SCHOOL_ID是school表的主键, School_address is the Address field in the SCHOOL table
#表School的外键为SCHOOL_ADDRESS, it corresponds to the primary key address_id of the ADDRESS of the table
(one) Insert Oneschool ———— sqlinsertrowstring:
Update SCHOOL set school_address=? where school_id=?
(only update the value of Foreign-key.) )
Delete Oneschool ———— sqldeleterowstring:
Update SCHOOL set school_address=null where school_id=?
(Strangely, setting Foreign-key to null does not know what the real meaning is?) )
Delete all school ———— sqldeletestring that belong to an address:
Update SCHOOL set school_address=null where school_address=?
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 "district ———— schools" is a bit farfetched for many-to-many relationships, just to facilitate comparison with the above One-to-many
#假设有一个关系表ADDRESS_SCHOOL, there are two fields address_id, school_id,
#这两个字段分别对应ADDRESS和SCHOOL两表的key
The SQL statement for Insert is: 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=?

For set operation (1), Hibernate executes (one) sqlinsertrowstring
For set operation (2), Hibernate executes (sqldeleterowstring)
For set operation (3), Hibernate executes (sqldeletestring)
Operation on set (4), old Schoolset because there is no address to belong to, so is all deleted, that is, first executed (sqldeletestring)
Then add a new Schoolset, then execute sqlinsertrowstring
The operation of Set (5) is actually the transfer of set from one Pojo to another pojo:
First, execute sqldeletestring, delete the school that otheraddress belongs to
Then, execute the sqldeletestring, delete the address of the original school
Finally, execute sqlinsertrowstring, add Otherschoolset to address

Summary: (1) for one-to-many, changing the set will allow Hibernate to execute a series of UPDATE statements without delete/insert the data
(2) for Many-to-many, changing the set and only modifying the data of the relational table will not affect the other side of the Many-to-many.
(3) Although the database operations of One-to-many and Many-to-many are different, the purpose is one: to maintain data consistency. The SQL that is executed is
Only the "bridge field" is involved, and no other fields are considered or changed, 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. ”
After commit, the two properties play differently when Hibernate is changed based on the Pojo object, and the Cascade property is set.
Generate a series of actions, such as updateaction,deleteaction,insertaction, and each action has an Execute method to execute the corresponding SQL statement.
After all these actions have been generated, hibernate executes them together, and the inverse property works before executing the SQL.
SQL is not executed when inverse=true, and SQL is executed when inverse=false.

The default value for 4.1.5 inverse is false, so the inverse property is associated update by default.

4.1.6 Recommendation: Set Inverse=false only for set + Many-to-many, other tags do not consider the inverse attribute.
Unfortunately, when you do not set the inverse property, inverse defaults to false.

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

4.2.2 cascade refers to whether the associated object (the passive side) performs the same operation synchronously when the master performs the operation.
The relationship between Pojo and its Relationship property is the relationship between the "master-passive side", and if the relationship property is a set, then the passive is one of the elements in the set.
For example: School (School) has three attributes: Region (Address), Principal (Themaster) and student (Set, element is student)
When executing session.delete (school), Cascade decides 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 associated operations because of cascading cascade. The previous operation is called a "master operation", and the latter action is called "associated operation".
Optional values for the Cascade property:
All: Associated operations are performed in all cases.
None: Associated operations are not performed in all cases. This is the default value.
Save-update: The associated operation is performed when Save/update/saveorupdate is executed.
Delete: The associated operation is performed when the delete is executed.

The specific implementation of the "associated Operation" is based on "Master action":
"Master Action" "Associate Operation"
Session.saveorupdate--session.saveorupdate (execution saveorupdate actually executes save or update)
Session.save----> Session.saveorupdate
Session.udpate-Session.saveorupdate
Session.delete-Session.delete

4.2.4 the sequence of master and associated operations is "save one first, then save many; Delete many first, delete one again, update the host, and then update the passive party"
For one-to-one, when its property constrained= "false" (the default), it can be considered a one-to-many relationship;
When its attribute constrained= "true", it can be regarded as many-to-one relationship;
For Many-to-many, it can be regarded as one-to-many.

For example: School (School) has three attributes: Region (Address), headmaster (Themaster, whose constrained= "false") and student (Set, element is student)
When Session.save (school) is executed,
The actual order of execution is: Session.save (Address);
Session.save (school);
Session.save (Themaster);
for (per student) {
Session.save (astudent);
}

When Session.delete (school) is executed,
The actual order of execution is: Session.delete (themaster);
for (per student) {
Session.delete (astudent);
}
Session.delete (school);
Session.delete (Address);

When Session.update (school) is executed,
The actual order of execution is: Session.update (school);
Session.saveorupdate (Address);
Session.saveorupdate (Themaster);
for (per student) {
Session.saveorupdate (astudent);
}
Note: The update operation is caused by cascading the saveorupdate operation instead of the update operation.
The difference between saveorupdate and update is that the former depends on whether the operation object is saved or not, and decides to perform an update or save

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

The default value for 4.2.6 cascade is false, so the inverse property is associated update by default.

4.2.7 Summary: Cascade (CASCADE) is the operation of an object, its properties (its cascade=true) also do this.


Comparison of 4.3 inverse and cascade
The two properties themselves do not affect each other, but are somewhat similar, and can trigger 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 is invalid.
Cascade is valid for relationship tokens.

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

More than a new school, Session.save (school)
Inverse causes Hibernate to execute:
For (each student of 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 (every student for school) {
Session.save (astudent); Perform a save operation on a student
}

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

4.3.22 The timing of the action is different:
Cascade: Cascade occurs when operating on the main control side.
Inverse: When flush (commit automatically executes flush), determines whether each set has a change for all set,hibernate in the session,
Execution of the corresponding SQL for the changed set, before execution, there will be a judgment: if (inverse = = true) return;

Can see cascade first, inverse in the rear.

4.3.3 Inverse has different effects on set + One-to-many and set + Many-to-many. Hibernate generates a different SQL.
The UPDATE statement is executed against the one-to-many,hibernate on the many side of the database table.
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, whether One-to-many or Many-to-many. Simply passes the operation to each element in the set. So it always updates many
-Side database tables.

4.3.4 Recommendation: Set Inverse=false only for set + Many-to-many, other tags are set to inverse=true regardless of the inverse attribute.

For Cascade, the one-to-one of many-to-one,many-to-many,constrained=true is not set to cascade Delete.

Hibernate collection mapping Inverse and cascade

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.