Hibernate (cascade) Cascade

Source: Internet
Author: User

I have already used the association in my previous notes, but it is mainly a demonstration. In this article, I will analyze it in detail!
Operation object using association relationship:
The associations between data objects are one-to-one, one-to-many, and many-to-many. In database operations, it is difficult to process the association between data objects using JDBC. For example, when deleting information about a class, you also need to delete the basic information of all students in the class. If you directly use JDBC to execute such cascade operations, it will be very complicated. Hibernate simply solves this cascade operation problem by declaring the associations and cascade relations between object in the ing file.
Use of one-to-one associations:
The one-to-one relationship is more relevant in real life. For example, the relationship between students and student IDs can be found through student IDs. One-to-one association can be implemented in hibernate in two ways: Primary Key Association and foreign key Association.
Primary Key Association:
The key of primary key Association is to associate two entities to share a primary key value. For example, student and card are in a one-to-one relationship, and their tables in the database are t_student and t_card respectively. They share a primary key value ID, which can be generated by the t_student or t_card table. The problem is how to make another table reference the generated primary key value? For example, how does the t_student Table reference the id value when it is not a long time ago? This requires the foreign generation mechanism of the primary key in the hibernate ing file!

To indicate the one-to-one relationship between student and card, we need to use the <one-to-one> mark in their respective ing files!
I have already written an example program for the one-to-one relationship. Here, only two ing files are provided. As follows:
Student Po ing information:
<? XML version = "1.0" encoding = "GBK"?>
<! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en"
Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>

<Hibernate-mapping>
<Class name = "hibernate. Po. tstudent" table = "t_student" lazy = "true"> <! -- Associate a class with a table -->
<ID name = "ID" type = "Java. Lang. Integer">
<Column name = "ID"/>
<Generator class = "increment"/>
</ID>
<Property name = "username" type = "Java. Lang. String">
<Column name = "username" length = "20"/>
</Property>
<Property name = "cardid" type = "Java. Lang. String">
<Column name = "card_id" length = "20"/>
</Property>
<Property name = "sex" type = "Java. Lang. String">
<Column name = "sex" length = "2"/>
</Property>
<Property name = "Age" type = "Java. Lang. Integer">
<Column name = "Age"/>
</Property>
<One-to-one name = "card" class = "hibernate. Po. tcard" Fetch = "join" cascade = "all"/>
</Class>
</Hibernate-mapping>
<! --
The lazy attribute of the class element is set to true, indicating delayed loading. If lazy is set to false
Indicates loading immediately. The two points are described below.
Load now: After hibernate acquires data from the database and assembles an object (such as student 1,
The object associated with the object will be assembled from the database immediately (for example, student ID 1 ).
Delayed loading: After hibernate acquires data from the database and assembles an object (such as student 1,
It will not immediately obtain data from the database to assemble the object associated with this object (such as student 1 ),
Instead, the associated object will be assembled from the database only when necessary.
The cascade attribute of the <one-to-one> element indicates whether the operation is cascade from the parent object to the associated object.
Can be obtained in the following ways:
None: when saving, deleting, or modifying the current object, the associated object (associated object) is not cascade.
Operation. It is the default value.
Save-Update: when saving and updating the current object, cascade save and update the affiliated object (temporary object,
Free object ).
Delete: when the current object is deleted, the secondary object is deleted cascade.
ALL: cascade operations in all cases, including Save-update and delete operations.
Delete-orphan: Delete the affiliated object from which the object is detached.
<One-to-one> the optional values of the fetch attribute of an element are join and select. The default value is select.
When the fetch attribute is set to join, it indicates join fetching: hibernate passes through
In the SELECT statement, use outer join to obtain the associated instance or set of objects.
When the fetch attribute is set to select, the query is crawled (select fetching ).
Returns a SELECT statement to capture the associated entities or sets of the current object. -->

Student ID card Po ing information:
<? XML version = "1.0" encoding = "GBK"?>
<! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en"
Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>

<Hibernate-mapping>
<Class name = "hibernate. Po. tcard" table = "t_card" lazy = "true">
<ID name = "ID" type = "Java. Lang. Integer">
<Column name = "ID"/>
<Generator class = "foreign">
<Param name = "property"> Student </param>
</Generator>
</ID>
<! -- ID: uses the foreign generation mechanism to reference objects codenamed student.
As the primary key and foreign key of the t_card table. Student
<One-to-one>
<Property name = "name" type = "Java. Lang. String">
<Column name = "name" length = "20"/>
</Property>


<One-to-one name = "student" class = "hibernate. Po. tstudent" constrained = "true"/>
<! -- Constrained = "true" indicates that the card references the primary key of student as the foreign key. -->
</Class>
</Hibernate-mapping>

Foreign key Association:
The key of foreign key association is that two entities have different primary keys, but one entity has a foreign key that references the primary key of another object. For example, suppose that student and card are a one-to-one relationship associated with foreign keys. The corresponding tables in the database are as follows: t_student table has a primary key ID, the t_card table has a primary key ID and a foreign key student_id. In addition, the key corresponds to the primary key ID of the t_student table, so the stuing information of student is not changed as above, the card ing file must be modified accordingly. As follows:
<Hibernate-mapping>
<Class name = "hibernate. Po. tcard" table = "t_card" lazy = "true">
<ID name = "ID" type = "Java. Lang. Integer">
<Column name = "ID"/>
<Generator class = "increment"/> <! -- No longer foreign -->
</ID>

<Property name = "name" type = "Java. Lang. String">
<Column name = "name" length = "20"/>
</Property>

<Role-to-one name = "student" column = "student_id" class = "hibernate. Po. tstudent" unique = "true"/>
<! -- The only multi-to-one is actually a one-to-one relationship -->
<! -- If Unique is set to true, DDL is used to generate a unique constraint for foreign key fields.
The one-to-one relationship of foreign key-associated objects has essentially become one-to-many bidirectional Association,
You should write their ing files directly according to one-to-many and multiple-to-one requirements. When unique is
True is actually a one-to-one relationship. -->

</Class>
</Hibernate-mapping>

Use of one-to-multiple associations
The relationship between one and many is very obvious. For example, the relationship between classes and students is a typical one-to-many relationship. When writing a program, one-to-multiple relationship can be implemented in two ways: one-way Association and two-way Association. The one-to-multiple relationship only needs to be mapped on one side, while the two-way one-to-multiple relationship needs to be mapped on both sides. The following uses group and student as examples to explain how to configure a one-to-many relationship.
Unidirectional Association:
One-way one-to-multiple relationships only need to be mapped on one side. Therefore, we only need to configure the group ing file:
<Hibernate-mapping>
<Class name = "hibernate. Po. Group" table = "t_group" lazy = "true">
<ID name = "ID" type = "Java. Lang. Integer">
<Column name = "ID"/>
<Generator class = "increment"/>
</ID>
<! -- Insert attribute indicates whether the mapped field exists in the SQL insert statement. -->
<Property name = "name" type = "Java. Lang. String" update = "true" insert = "true">
<Column name = "name" length = "20"/>
</Property>

<! -- The type of the field described by the set element is Java. util. Set.
Inverse is used to represent the passive end of a bidirectional Association. Inverse Value
If the value is false, the party is responsible for maintaining the association.
Sort sorting relationship. The optional value is unsorted ).
Natural (natural sorting ).
Comparatorclass (the sort algorithm is specified by a type that implements the java. util. comparator interface .)
<Key> the column attribute of the child element specifies the foreign key of the associated table (t_student table.
-->
<Set name = "Students"
Table = "t_student"
Lazy = "true"
Inverse = "false"
Cascade = "all"
Sort = "unsorted">
<Key column = "ID"/>
<One-to-learn class = "hibernate. Po. tstudent"/>
</Set>
</Class>
</Hibernate-mapping>
Bidirectional Association:
If you want to set one-to-multiple bidirectional associations, you also need to use the <strong-to-one> mark in the ing file of the "multiple" side. For example, in the one-to-many bidirectional association between group and student, in addition to the group ing file, the following code must be added to the student ing file:
<Role-to-one name = "group"
Class = "group"
Cascade = "NONE"
Outer-join = "Auto"
Update = "true"
Insert = "true"
Column = "ID"/>

Inert and update set whether to insert and update the joined fields specified by the column attribute.
In addition, set the inverse of the <set> element in group. HBM. XML to true.

Use of multiple-to-multiple associations
Student and course are many-to-many relationships. You need to use another connection table (such as student_course) When ing many-to-many relationships ). The student_course table contains two fields: courseid and studentid. In this example, the ing files are marked with the <strong-to-short> label and the following description is added to the student ing file:
<Set name = "courses"
Table = "student_course"
Lazy = "false"
Inverse = "false"
Cascade = "Save-Update">
<Key column = "studentid"/>
<Subtitle-to-extract class = "Course" column = "courseid"/>
</Set>
Add the following to the corresponding course ing file:
<Set name = "Students"
Table = "student_course"
Lazy = "false"
Inverse = "true"
Cascade = "Save-Update">
<Key column = "courseid"/>
<Role-to-define class = "student" column = "studentid"/>
</Set>
Add link:
First, write a program to see what courses a student named Bill has chosen:
// Obtain the student object representing Bill
Student Stu = (student) Session. createquery ("from student s where S. Name = 'bill '"). uniqueresult ();
List list = new arraylist (STU. getcourses ());
For (INT I = 0; I <list. Size (); I ++)
{
Course course = (course) list. Get (I); // gets the course object
System. Out. println (course. getname (); // print out the list of courses selected by Bill.
}
Now, Bill also wants to take the chemistry course. This is just to add a join to the chemistry for the programmer. That is to say, add a new record in the student_course table, and the t_student and t_course tables do not need to be changed.
// Obtain the student object representing Bill
Student Stu = (student) Session. createquery ("from student s where S. Name = 'bill '"). uniqueresult ();
Course course = (course) Session. createquery ("from course c Where C. Name = 'chemistry '"). uniqueresult ();
// Set the association between Stu and Course
Stu. getcourses (). Add (course );
Course. getstudents (). Add (Stu );
Delete Association:
It is relatively easy to delete associations. You can directly call the remove () method of the object set to delete unwanted objects. For example, to delete the politics and chemistry courses from the student Bill's course selection list, the program code is as follows:
// Obtain the student object representing Bill
Student Stu = (student) Session. createquery ("from student s where S. Name = 'bill '"). uniqueresult ();
Course course1 = (course) Session. createquery ("from course c Where C. Name = 'politics '"). uniqueresult ();
Course course2 = (course) Session. createquery ("from course c Where C. Name = 'chemistry '"). uniqueresult ();
Stu. getcourse (). Remove (course1); // delete a Politics Course
Stu. getcourse (). Remove (course2); // Delete A Chemistry Course
Running the above program will delete these two records from the student_course table, but the t_student and t_course tables do not change.

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.