Cascading relationships (most of the content comes from the Java EE Lightweight solution The rest is my idea)

Source: Internet
Author: User
Tags what sql

1. Cascading relationships

Objects persisted in Hibernate programs are referenced to each other through association relationships. Object for operations such as Save, update, and delete, it is sometimes necessary for the associated object to perform the appropriate actions, such as assuming that the associated object will perform the same operation synchronously when an action is taken by an active object that requires an associated relationship. This problem can be solved by using Hibernate's Cascade (CASCADE) functionality.

For example, when trying to delete a customer object, Hibernate decides whether to delete all the order objects corresponding to that object by cascading relationships. Cascade is a property of the <set> element that is commonly used and is described in the following table:
Property value Describe
None Default value, which indicates that there are no cascading operations between the associated objects
Save-update Indicates that the active object performs a save or update operation on the associated object when the Save (), update (), and Saveorupdate () methods are called
Delete Indicates that the active object performs a delete operation on the associated object when the delete () method is called
Delete-orphan Used in the 1-n Association, which means that the active object calls the Delete () method when it removes the associated object that is not referenced by any one of the associated objects, and is used in the parent-Child Association object.
All Federated use equivalent to Save-update and delete
Note: In the actual development, the level of unicom is commonly used in 1-n and 1-1 association relationships. The use of cascading operations for N-1 and n-n associations is meaningless.   In addition, the Cascade attribute value Save-update is most commonly used. Next, we'll show you how to use cascading, and what SQL statements to use with cascading? Suppose the customer class, Order class is as follows: requirements: When you add a customer object, all orders for that customer are also saved. Add the following code to the Businessservice:
1  Public classbusinessservice{2      Public Static voidMain (string[] args) {3Customer customer =NewCustomer ("Lisi", "123", "John Doe", "Qingdao", "123123");4Order order =NewOrder ("3",NewDate (), 1000.0);//did not pass in the Customer object5         //Establish association relationships to achieve cascading saving6 customer.getorders (). Add (order);7 8Session session =hibernateutils.getsession ();9 TenTransaction trans =session.begintransaction (); One Session.save (customer); A trans.commit (); - hibernateutils.closesession (); -     } the}

1 Customer.hbm.xml2 <hibernate-mapping Package= "Com.haiersoft.ch05.pojos">3     <classname= "Custoemr"Table= "CUSTOMER">4     ... ... Omit other code5         <!--1-n Association Relationship -6         <Setname= "Orders"Cascade= "Save-update">7             <Keycolumn= "customer_id"/>8             <One-to-manyclass= "Order"/>9         </Set>Ten     </class> One </hibernate-mapping>
In the code above, cascading save or update operations are configured, and when the customer object is saved, the corresponding order object is cascaded. When you run the Main method, hibernate executes the following SQL statements: INSERT INTO CUSTOMER (USERNAME, PASSWORD, Realname, ADDRESS, MOBILE) VALUES (?,?,?,?,? )   ①insert into ORDERS (OrderNo, ORDERDATE, Total, customer_id) VALUES (?,?,?,?)   ②update ORDER SE T customer_id =?  where id=?   ③  in the above results, two INSERT statements and an UPDATE statement were executed. Hibernate first inserts a record (①) into the Customer table, and then inserts a record in the Orders table that does not have a customer parameter, that is, the parameter customer_id in the inserted sentence is not a value (②), Then you need to use the third UPDATE statement, which gets the ID value of the customer_id, Orders table based on the record of the first two statements, and assigns the customer_id foreign key (③) to the records in the Orders table. This completes the association between the two tables.   SUMMARY: Cascade relationship facilitates our data manipulation of related relationships, with hibernate cascading, you just have to include the active association of the Cascade relationship with the object of the associated party, then we just have to operate on the active side, As to the data of the associated party, it will be processed according to our relationship. In other words, the customer object in the above example is an active associated party, and order is the associated party. When it is necessary to insert a customer record into the database, and also to insert its corresponding order record into the database, then we just need to add the order object to the Customer object's Orders property, and directly to the customer to operate on it, The order object does not need to pass in the customer parameter, nor does it need to manually save the order object to the database, and hibernate will help us out.  2. Cascade control inversion in the 1-n Association, the control is usually given to the "N" side, which can be implemented in the <set> element by configuring the inverse property, when inverse= "True" indicates that an association relationship is maintained by the other party. The modified Customer.hbm.xml code is as follows:<!--configuration control inversion--><set name= "orders" inverse= "true" cascade= "Save-update" ><key Column= "customer_id"/><one-to-many class= "order"/></set> through the above configuration, set the associated control to the Order object, So the order object must be associated to the object before saving the customer object, as in the following code: 
1  Public classbusinessservice{2      Public Static voidMain (string[] args) {3         //Add customer and order information4Customer customer =NewCustomer ("Lisi", "123", "John Doe", "Qingdao", "123123123");5Order order =NewOrder ("3",NewDate (), 1000.0);6         //Establish association relationships to achieve cascading saving7 customer.getorders (). Add (order);8         //the order object must be associated with the customer object for inverse to work9 Order.setcustomer (customer);Ten  One  ATransaction trans =session.begintransaction (); - Session.save (customer); - trans.commit (); the hibernateutils.closesession (); -  -     } -}

In the preceding code, the statement "Order.setcustomer (Customer)" is used to implement the Association of order to the Customer object, and hibernate executes the following two INSERT statements when the main () method is run.

Insert into CUSTOMER (USERNAME, PASSWORD, Realname, ADDRESS, MOBILE) VALUES (?,?,?,?,?)   ①insert into ORDERS (OrderNo, ORDERDATE, Total, customer_id) VALUES (?,?,?,?) ② Summary: When the associated control is given to the "N" side, the cascade operation between the two associated objects can be completed without the need to execute the UPDATE statement.

Cascading relationships (most of the content comes from the Java EE Lightweight solution The rest is my idea)

Related Article

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.