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 classstaff {Private intid; PrivateString name; PrivateDept Dept; }//Staff.hbm.xmlclassName= "onetomany.staff" table= "staff" > <id name= "id" column= "id" >
         //set The increment, This should be understood,<generatorclass= "increment" ></generator> </id> <property name= "name" ></property>//Dept attribute in name:staff entity class, Column: Dept Class class:staff associated with field names in child tables that are decorated with foreign key constraints<many-to-one name= "dept" column= "deptid"class= "onetomany.dept" ></many-to-one> </class>

Dept.java and Dept.hbm.xml

 public classDept {Private intid; PrivateString name; PrivateSet<staff> Staffset =NewHashset<staff>(); ..... }//Dept.hbm.xmlclassName= "onetomany.dept" table= "Dept" > <id name= "id" column= "id" > <generatorclass= "increment" ></generator> </id> <property name= "name" ></property>//key: The name of the field that the child table is decorated by a foreign key constraint<set name= "staffset" > <key column= "deptid" ></key> <one-to-manyclass= "onetomany.staff"/> </set> </class> 

Configure a two-way, One-to-many Association relationship

Test class

 //create new Department  
Dept Dept = new Dept (); Dept.setname ( er Department //create A new employee staff member = new staff (); Staff.setname ( "www"
//add Department staff.setdept (dept) to staff;
//add staff to department dept.getstaffset (). add (staff);
//save 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" Set the cascade here in the associated properties, Indicates that the entity class object, if it is in the save or update or Saveorupdate operation, The associated object (provided that the object, that is, the Reference object variable has a value) to do the corresponding operation, so in the test class only need to write session.save ( staff);

        New Dept ();        Dept.setname ("er department");                 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

Other should know, say this all-delete-orphan: what is an orphan node, for example, There are 5 students in a class, then graduated, 5 students go, then this class is an empty class, how to express this relationship in the database table, The student table has the foreign key to the class table in the primary key, when the student table students degrees, then the class table corresponding to the class also become an orphan node, so set this cascade attribute, is to delete the orphan Node.

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.xmlclassName= "onetomany.dept" table= "Dept" > <id name= "id" column= "id" > <generatorclass= "increment" ></generator> </id> <property name= "name" ></property>//inverse= "true", Let the other side to maintain the relationship, at this time the Cascade settings here is not used, because it does not maintain the relationship, it also fails. <set name= "staffset"inverse= "true" cascade= "save-update"> <key column= "deptid" ></key> <one-to-manyclass= "onetomany.staff"/> </set> </class> 
//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 to let oneself this side 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), the role of two, one is to let the two sides have associated with the object, in the set cascade, can only save one side, The other party has saved the Cascade. 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.

        New Dept ();        Dept.setname ("er department");                 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, and the Dept Party's Association Fails. therefore, it needs to be annotated, in the staff side of the set cascade,        save staff on line  session.save (staff);  Cascading saves the dept, and it sets the value of the Foreign key field itself, which is to maintain the 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.xmlclassName= "onetomany.dept" table= "Dept" > <id name= "id" column= "id" > <generatorclass= "increment" ></generator> </id> <property name= "name" ></property>//inverse= "false", Let oneself maintain relations, at this time here the Cascade setting is effective, the other Party's eascade Failure. <set name= "staffset"inverse= "false"cascade= "save-update" > <key column= "deptid" ></key> <one-to-manyclass= "onetomany.staff"/> </set> </class> //Staff.hbm.xml<className= "onetomany.staff" table= "staff" > <id name= "id" column= "id" > <generatorclass= "increment" ></generator> </id> <property name= "name" ></property>//this cascade fails, that is, if only the staff is saved, it is not cascaded to save Dept. <many-to-one name= "dept" column= "deptid"class= "onetomany.dept"cascade= "save-update"></many-to-one> </class>

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

 Dept Dept = new   Dept ();                Dept.setname ( er Department  = new   staff ();       Staff.setname ( "www" //this sentence can be removed, staff will not be in the Management.        
//staff.setdept (dept); Because dept to maintain the relationship, so he must know how to relate to the foreign key relationship and know the associated object, so that the role of this sentence can be a function of the cascade to reflect the role, 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, Saving Only Dept is Ok. // 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.