Hibernate (VI) CASCADE (CASCADE) and inverse relationship

Source: Internet
Author: User
Tags set set

Preface

Before writing this article, I also checked a lot of information to find out the relationship between the two and their own things, but Baidu a search, most of the blog post feel said Foggy, may Bo master himself clear is how one thing, but to a person who do not understand or smattering people see, others also do not understand the relationship among them, So when I write my own blog, I will try to use the popular language to describe a concept, hope to do their own strength to help you understand. Light look at my is not, the most important thing is to do their own practice once again, can draw the same conclusion, that means that understand, in I do not understand the time, I will go to their own realization of it, try again, slowly summed up the law.

--wh

First, foreign key

Why should I take this alone? Because yesterday I found myself to this foreign key concept originally understanding deviation, and many people estimate and I like, to this thing understand wrong, now say a what misunderstanding.

1, the foreign key of this watch is DeptID? 2. Does this table have a foreign key?

Most people here say the foreign key, degree refers to the field name in a table that is constrained by a foreign key. This is a lot of people from the beginning of the default, in fact, not yet,

Explanation: For each table with a FOREIGN KEY constraint constraint, the foreign KEY constraint relationship is given a name, which can be learned from the statement that sets the FOREIGN KEY constraint on the table.

CONSTRAINT foreign Key name FOREIGN key by foreign key constraint decorated field name REFERENCES parent table name (primary key)

So, most people in the mouth of the foreign key, refers to the foreign key constraints decorated by the field name, foreign key relationship has its own name. Everyone needs to figure out that although the usual impact is not small, but to the really critical place, you may be the small knowledge point to the circle.

II. Cascade (Cascade) Relationship

Why take this alone to tell an article? Because I am looking at other people's blog, I put cascade and inverse and several related relations together, and is that kind of a description, write a relatively simple, actually understand is really very simple, but for the beginning to learn people, this will be a big disaster, smattering is the most uncomfortable.

Explanation: Cascading, is the operation of an object, it will be associated with the object is also carried out the corresponding operation, the associated object meaning refers to, for example, the first two lessons in a one-to-many relationship, class and students, student entity class, there is a reference variable classes object, If the reference variable that holds the Classes object has a value, then the value is the associated object, and when you save the student, if the reference variable that holds the Classes object has a value, then the classes object is also saved, which is the function of cascading.

Said plain English this meaning is difficult to put in place, to give an employee and department two-way one-to-many examples.

Create an experimental environment (this can be implemented on your own, practice the configuration of the associated relationship)

First you have to figure out the diagram of the two tables, and in all the subsequent analyses, the degree will be analyzed with this relationship, and you won't be blindfolded.

              

Staff.java and Staff.hbm.xml

public class Staff {    private int id;    private String name;    Private Dept Dept; }//staff.hbm.xmlSet the increment, this should be read,            <generator class= "increment" ></generator>        </id>        < Property name= The Dept attribute in the "name" ></property>    //name:staff entity class, Column: The Dept class associated with the field name Class:staff that is decorated by the foreign key constraint in the child table        <many-to-one name= "dept" column= "DeptID" class= "onetomany.dept" ></many-to-one>            </class >

Dept.java and Dept.hbm.xml

public class Dept {    private int id;    private String name;    Private set<staff> Staffset = new hashset<staff> (), .... }//dept.hbm.xml

Configure a two-way, one-to-many association relationship

Test class

Create a new department
Dept Dept = new Dept (); Dept.setname ("ER department");
Create a new Employee staff member (). Staff.setname ("www");

Add Department staff.setdept (Dept) to the staff;
Add Employee Dept.getstaffset () to the Department. Add (staff);
Preservation Department session.save (dept);
Save Employee Session.save (staff);

As a result, two instances are definitely saved to the corresponding table.

          

When we do not know anything, we will save the department, and then save the staff, so that two records into the response table, if the use of cascading, then it is not necessary to write such a trouble.

For example, when we want to save the staff, we also save the dept in passing.

Other unchanged, add cascading properties in Staff.hbm.xml

<class name= "Onetomany.staff" table= "Staff" >
<id name= "id" column= "id" >
<generator class= "Increment" ></generator>
</id>
<property name= "Name" ></property>
<many-to-one name= "Dept" column= "DeptID" class= "onetomany.dept" cascade= "Save-update" ></many-to-one>

</class>

Cascade= "Save-update" is set in the associated property here to indicate that the entity class object will be associated with the object if it is in save or update or saveorupdate operation (if there is a value for this object, that is, the Reference object variable) The corresponding operation, so in the test class only need to write the Session.save (staff); And do not need to write Session.save (dept). Because there is a cascade of existence,

        Dept Dept = new Dept ();        Dept.setname ("ER department");                Staff and staff: new staff ();        Staff.setname ("www");
This is the setting of the associated object staff.setdept (dept); This sentence can have no, specific role in explaining inverse when said Dept.getstaffset (). Add (staff); Session.save (dept);
Just save the staff and the dept will be saved as well. Session.save (staff);

The result, as we thought, was that the Cascade saved the Dept object.

        

Of course, this is only in the staff of the side to set up the cascade, you can also set up a cascade in the dept, so that only save dept, you can save the staff. Here is just a save object to do an example to explain, cascading is not necessarily just cascade save there are many other properties, see the following summary

Summarize:

Knowing the role of cascading, let's look at the cascading properties

The Cascade relationship has the following types

All: Associated operations are performed in all cases, i.e. save-update and delete.
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-delete-orphan: When a node becomes an orphan node in an object graph, the node is deleted

We use save-update, that is, if the associated object is not recorded in the table, it will be the save, if any, to see if there is a change, it will be updat

Others should know, say this all-delete-orphan: What is an orphan node, for example, classes and students, a classes table, a student table, a student table with 5 students in the data, 5 of its students belong to this class, That is, the foreign key fields of the 5 students point to that class, and now delete one of the students (remove), the data operation is only to set the student's foreign key field in the student table to NULL, that is, the student is not a class, so called the student as an orphan node, We should have removed him completely, but the result is not as good as we thought, so setting this cascading property is to remove the orphan node. Which is to solve this kind of situation.

Cascade relationship is simple, it is such a few, not difficult to understand. The key is to understand the corresponding operation of the associated object, which refers to who, knowing this, will know why in the mapping file that location to set the cascading properties.

Third, inverse

This is a very difficult point for me to understand, at first, because a lot of people did not tell him clearly.

The value of the inverse is a Boolean value that can be set to TRUE or false. If a party's mapping file is set to True, the mapping relationship (one-to-many, many-to-many, etc.) is allowed to maintain the relationship. If False, the relationship is maintained on its own. The default value is true. And this property can only be set at one end. Like a one-to-many, this end. This is the side setting that has the set set.

Maintain relationship: What relationship does it maintain? Includes two areas

1, that is to maintain the relationship between foreign keys, popular point, is which side to set the foreign key constraints of the field value. Take the above example, the Staff and dept two tables regardless of what the operation, as long as the relationship to another table, it is inevitable to manipulate the foreign key field, for example, the staff to query their own department, you have to be the foreign key constraints of the field value to dept in the primary key to find, If dept want to find out which employees in their department, they can compare their primary key values with the foreign key fields in the staff, and the same value is the employee of their own department. This is a query operation, now if it is added, a record is added to the staff table, and the department belongs to one of the Dept tables, the staff has a field that is modified by the FOREIGN KEY constraint, which is assigned to the foreign key field through the INSERT statement of the staff. or let the Dept object be assigned a value using the UPDATE statement, and two can manipulate the value of the foreign key field, who is going to manipulate it? If you do not set, two will operate, although there is no problem, but it will affect performance, because the staff operation, the use of the INSERT statement can set the value of the foreign key field, but Dept will also operate on it, and use the UPDATE statement, so that, This update will show a lot of surplus.

2, maintain a cascade of relations, that is, if the other side to maintain the relationship, then their own side of the cascade will be invalidated, the other side set up the cascade useful, if you maintain the relationship, then their own side of the association useful, but the other set of cascading will be invalidated.

In the above results, will send 5 SQL statements, the first two does not matter, look at the following three. See the last one, that's what we call a jump UPDATE statement. This confirms what we said above, with two tables maintaining a foreign key relationship.

Hibernate:     Select        max (ID)     from        depthibernate:     select        max (ID)        from staff Above these two no tube, this is set the primary key generation strategy for increment will send these two sentences. Get the largest ID value in the database table before you know how many ID values to assign next time.
-------------------------------------------------
Hibernate: insert into dept (name, id) values (?,?) Hibernate: INSERT INTO staff (name, DeptID, id) values (?,?,?) Hibernate: update staff set deptid=? where id=?

To solve this problem, use the inverse attribute to allow only one party to maintain the relationship (maintaining the foreign key value).

Set this property on one side, Inverse=true is the default, that is, let the staff maintain the relationship.

dept.hbm.xml
Staff.hbm.xml
<class name= "Onetomany.staff" table= "Staff" >
<id name= "id" column= "id" >
<generator class= "Increment" ></generator>
</id>
<property name= "Name" ></property>
This cascade is useful because it is the party that maintains the relationship.
<many-to-one name= "Dept" column= "DeptID" class= "onetomany.dept" cascade= "Save-update" ></many-to-one>

</class>

Note: Dept.getstaffset (). Add (staff); or staff.setdept (dept); There are two functions, one is to let the two sides have associated with the object, in the setting cascade, can only save one side, the other side of the Cascade saved. Another function is to set the relationship so that the staff or dept will know what the relationship is, that is, the ability to assign values to the foreign key field. Because we set up to let staff manage, so dept.getstaffset (). Add, this sentence can be commented out, is superfluous, tell him how to set the value of the foreign key field, he will not go to set up, just want to set up to make it good.

        Dept Dept = new Dept ();        Dept.setname ("ER department");                Staff and staff: new staff ();        Staff.setname ("www");        Staff.setdept (dept);                Dept.getstaffset (). Add (staff);                    Session.save (dept);//The Cascade is set on the Dept side, but only the save Dept,staff is not cascaded, because the relationship dept is no longer in the way, the Dept Party's Association fails. So it is necessary to annotate it, set up cascade in staff, save staff on line        Session.save (staff),//Cascade Save Dept, and set the value of foreign key field, that is, maintain foreign key relationship.

Look at the SQL statements sent, and if the guesses are correct, you won't be sending an UPDATE statement this time.

Hibernate:     Select        max (ID)     from        depthibernate:     select        max (ID)        from Staff------------------------------------------------------Hibernate:     insert     into        dept        ( Name, id)     values        (?,?) Hibernate:     INSERT INTO staff        (name, DeptID, id)     values        (?,?,?)

If the inverse is set to false. The dept to set the foreign key value, staff can not tube,

dept.hbm.xml

Because with the above configuration, see how the code of the test is written

      Dept Dept = new Dept ();        Dept.setname ("ER department");                Staff and staff: new staff ();        Staff.setname ("www");       
Staff.setdept (dept); Because dept to maintain the relationship, so must let him know how to relate to the foreign key relationship and know the associated object, so that the role of this sentence can also be the role of the cascade to reflect, but also to reflect the foreign key relationship, Dept.getstaffset (). Add (Staff ); Session.save (dept);//Because Save-update cascade is set on the dept side, it is only possible to save Dept. //session.save (staff);

This result will have an UPDATE statement, because is dept to manage, he wants to manage, must send the update

Hibernate:     Select        max (ID)     from        depthibernate:     select        max (ID)        from staff Above these two no tube, this is set the primary key generation strategy for increment will send these two sentences. Get the largest ID value in the database table before you know how many ID values to assign next time. -------------------------------------------------Hibernate:     insert     into        dept        (name, id)     Values        (?,?) Hibernate:     INSERT INTO staff        (name, DeptID, id)     values        (?,?,?) Hibernate:     update        staff     set        deptid=?     where        id=?

Iv. Summary

Here, the roles of inverse and cascade have been explained.

1, inverse permissions on the cascade, meaning that cascade is useful, but also to see inverse this attribute

2, the role of inverse: in the mapping relationship, let one side to maintain the relationship, the advantage is to improve performance, without repeated maintenance. Maintain two relationships and look at

2.1 Controlling whether a cascade relationship is valid

Cascade is effective, it depends on the value of Inserve, if it is their own side to maintain the relationship, then cascade effective, and vice versa

2.2 Controlling foreign key relationships

This is done by having an instance reference to each other (which may be set or a variable of a single storage object), so that you have the ability to control the foreign key relationship, and then look at the value of the Inserve.

3, inverse can only be set in one party, and the default value is true, that is, do not set inverse, the default is to let many of the party to maintain the relationship, this is generally in the two-way, foreign key relationship in order to set the value of inverse, if it is unidirectional, only one side has the right to maintain relations.

4, in the future code, the first to understand the relationship, in order to write the best performance code. By learning these two properties, in the test code, you need not be so troublesome, just consider the maintenance of the relationship side, the other side will be automatically saved.

5. If you are not sure how many SQL statements you have sent to the test code, you can look ahead to the article that explains the first-level cache and three states, and how many SQL statements are sent through the snapshot area and session scope.

  

Hibernate (VI) CASCADE (CASCADE) and inverse relationship

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.