Hibernate manipulating objects with association relationships

Source: Internet
Author: User
Tags generator

manipulating Objects with association relationships

The correlation relationship between data objects has a pair of one or one-to-many and many-to-many associations. In database operations, the association relationship between data objects is difficult to use with JDBC. This section explains how to handle the association between these objects in hibernate. This section uses 4 classes, each of which are student (student), card (student ID), Group (Class), and Course (course), as shown in the association relationship 1-1. There are cascading (cascade) issues with these entities. For example, when you delete a class's information, you also delete the basic information for all students in that class. It is cumbersome to perform this cascade operation directly using JDBC. Hibernate is a simple way to solve this cascade operation problem by declaring the relationship between entity objects and cascading relationships in the mapping file.

Figure 1-1 Object Correlation diagram

Use of one-to-one correlation

The relationship between one and the other is more common in real life, such as the relation between student and student ID, and students can be found through Student ID card. There are two ways to implement a one-to-one relationship in Hibernate, namely, primary Key association and foreign Key Association.

1. Associate with primary key

The focus of the primary key association is that the associated two entities share a primary key value. For example, student and card are a pair of relationships, and their corresponding 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 table or the T_card table. The question is how do you let another table refer to the primary key value that has already been generated? For example, the T-student table fills in the value of the primary key ID, and how does the T_card table reference it? This requires using the foreign generation mechanism of the primary key in the Hibernate mapping file. In order to represent a one-to-one association between the student and the card, the <one-to-one> tag is used in the mapping file Student.hbm.xml and Card.hbm.xml of the student and card, as shown in routine 1-2.

Routine 1-2 Student.hbm.xml

----------------------------------------------------- ------------------------------------------< XML version= "1.0"?><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

Load now: Indicates that hibernate obtains data from the database, assembles an object (such as Student 1), and then immediately takes the data from the database and assembles the objects associated with the object (for example, Student ID 1).

Lazy loading: Indicates that hibernate obtains data from the database, assembles an object (such as Student 1), does not immediately take the data from the database, assembles the object associated with the object (for example, Student ID 1), but waits until necessary to obtain data from the database and assemble the associated object.

The Cascade property of the <one-to-one> element indicates whether the operation is cascaded from the parent object to the associated object, and it is evaluated as follows. None: When you save, delete, or modify an object, do not cascade its attached objects (associated objects). This is the default setting. Save-update: When you save, update the current object, Cascade Save, update the satellite objects (temporary objects, free objects). Delete: Cascade deletes the satellite object when the current object is deleted. All: Cascade operations in all cases, which includes save-update and delete operations. Delete-orphan: Removes the subordinate object that is associated with the current object.

The optional value for the Fetch property of the <one-to-one> element is join and select, and the default value is select. When the fetch attribute is set to join, the connection fetch is represented (join fetching): Hibernate obtains an associated instance or associated collection of an object by using a OUTER join (outer join) in the SELECT statement. When the Fetch property is set to select, the query fetch (select fetching): You need to send a separate SELECT statement to fetch the associated entity or collection of the current object.

The Cascade property of the <one-to-one> element in routine 1-3 is set to "all", which indicates that when an student object is added, deleted, and modified, the card object is added, deleted, and modified.

Routine 1-3 Card.hbm.xml

-------------------------------------------- ---------------------------------------------------< XML version= "1.0"?><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

In routine 1-3, Card.hbm.xml's primary key ID uses the foreign key (foreign) generation mechanism, referencing the primary key of the "student" object as the primary key and foreign key of the Card table. Student is defined in the <one-to-one> element of the mapping file, which is the code name of the student object. The properties of the <one-to-one> element constrained= "true" means that the card refers to the student's primary key as a foreign key.

It is important to note that a pair of get/set methods should be added to the student class accordingly:

Public Card Getcard () {return this.card,} public void Setcard (card) {this.card = card;}

In the card class, you should also add a pair of get/set methods accordingly:

Public Student getstudent () {return this.stu,} public void Setstudent (Student stu) {this.stu = stu;}

The method of manipulating the student and card objects in the client tester is shown in routine 1-4. Routine 1-4 Client test program

Package test;

Import org.hibernate.*; Import org.hibernate.cfg.*; Import Java.io.File; Import java.util.List;

public class Test {public static void main (string[] args) {File file = new file ("D://eclipse3.2//workspace//hibernatetes T//hibernate.cfg.xml "); Configuration conf = new configuration (). Configure (file); Sessionfactory SF = Conf.buildsessionfactory (); Session session = Sf.opensession (); Transaction tx = Session.begintransaction (); New Student Object Student stu = new Student (); Stu.setname ("Walker"); Stu.setsex ("male"); Stu.setage (22);

New Card Object card = new card (); Card.setname ("Walker"); Sets the association between the student object and the card object Stu.setcard (card); Card.setstudent (Stu); This sentence cannot be omitted, otherwise the card will not know where to get the primary key value try {Session.save (stu); Tx.commit (); Session.close (); System.out.println ("Data has been inserted into DB."); } catch (Hibernateexception e) {e.printstacktrace (); Tx.rollback (); Session.close ();}} }

After running the above code, the corresponding data will be inserted in the T_student table and the T_card table.

2. External Key Association

The main point of a foreign key association is that two entities each have a different primary key, but one of the entities has an external key that references the primary key of another entity. For example, if the student and the card are foreign key-related relationships, they are in the database the corresponding table is the T_student table and the T_card table, the T_student table has a primary key Id,t_card table has a primary key ID and a foreign key stu_id, The key also corresponds to the primary key ID of the student table.

Student mapping file Student.hmb.xml see routine 1-2. But the card mapping file Card.hbm.xml to make corresponding changes, as shown in example 1-5. Routine 1-5 Card.hbm.xml

---------------------------------------------------------------------------------- ------------------------------------

<!--associating classes with tables--> <!-- No longer foreign--></generator> <many-to-one name= " Student "class=" student "column=" stu_id "unique=" true "/> <!--the only many-to-one, actually become a single relationship--> hibernate-mapping>

In routine 1-5, the Name property of the,<many-to-one> element declares the codename of the Foreign Key association object, the class attribute declares the foreign key association object's classes, and the Column property declares the field name of the foreign key in the data table. The unique attribute indicates that a unique constraint is generated using the DDL for the foreign key field.

The one-to-one relationship of the other key-related objects is essentially a one-to-many bidirectional association, and the mapping file should be written directly according to the requirements of a pair of many and many pairs. When the unique attribute of the <many-to-one> element is set to true, a many-to-one relationship actually becomes a a-to-a relationship.

The method of manipulating the foreign Key association object in the client program is described in routine 1-4.

Use of a one-to-many association relationship

One-to-many relationships are common, such as fathers and children, and the relationship between classes and students is a good one-to-many relationship. When actually writing a program, a one-to-many relationship is implemented in two ways: unidirectional and bidirectional. One-way-to-many relationships only need to be mapped on a single side, while two-way pairs require a mapping configuration on both sides of the association. The following is an example of how to configure a one-to-many relationship with group (class) and student (students).

1. One-Way Association

One-to-many relationships only need to be mapped on a single side, so we only configure the group (Class) mapping file Group.hbm.xml, as shown in routine 1-6.

Routine 1-6 Group.hbm.xml

<!--associating classes with tables--> </generator> <set name= "Students" table= "T_student" lazy= "false" inverse= "false" cascade= "All" sort= "unsorted" >< key Column= "ID"/>< one-to-many class= "test. Student "/></set>

The Insert property of the,<property> element in the mapping file above indicates whether the mapped field appears in an INSERT statement in SQL; The Update property indicates whether the mapped field appears in the SQL UPDATE statement.

The field that the <set> element describes (in this case, students) corresponds to the type Java.util.Set, and its various properties have the following meanings.

Name: Field name, in this case the field name is students, which belongs to the Java.util.Set type. Table: Associated table name, in this case, the associated data table name for students is t_student. Lazy: whether to delay loading, lazy=false means to load immediately. Inverse: Used to represent one end of a passive side in a bidirectional association, and a party with a value of false inverse is responsible for maintaining the association relationship. The default value is False. In this case, the group will be responsible for maintaining the association between it and student. Cascade: cascading relationships; Cascade=all means cascading operations in all cases, including save-update and delete operations. Sort: Sorting relationships, with selectable values of unsorted (not sorted), natural (natural sort), Comparatorclass (by specifying a sort algorithm for a type that implements the Java.util.comparator interface). The column property of the <key> child element specifies the name of the associated class for the foreign key,<one-to-many> child element of the associated table (t_student table in this example).

In addition, add the following Get/set method to the group class:

Private Set students;

Public Set getstudents () {return this.students,} public void Setstudents (Set stu) {this.students = stu;}

If we want to add a student object to a class, the following code is implemented:

Transaction tx = Session.begintransaction (); Student stu = new Student (); Stu.setname ("Walker"); Stu.setsex ("male"); Stu.setage (22);

Group.getstudents (). Add (Stu);

Session.save (group); Tx.commit ();

2. Bidirectional correlation

If you want to set up a one-to-many bidirectional association, you also need to use the <many-to-one> tag in the "many" side of the mapping file. For example, in a one-to-many bidirectional association between group and student, in addition to the group mapping file Group.hbm.xml and the group class are set up and modified, you also need to include in the student mapping file STUDENT.HBM.XM:

<many-to-one name= "group" class= "test. Group "cascade=" None "outer-join=" Auto "update=" true "insert=" true "column=" ID "/>

Properties such as name, class, and so on are explained earlier, and only the insert and update properties are described here. Insert and update sets whether to insert and update the associated fields specified by the column property. In the student class, add a pair of get/set methods accordingly:

Public Group Getgroup () {return this.group,} public void Setgroup (Group g) {this.group = g;}

Also, set the value of the inverse property of the <set> element in Group.hbm.xml (as shown in routine 1-6) to true, as shown below.

<set name= "Students" table= "T_student" lazy= "false" inverse= "true" cascade= "All" sort= "unsorted" >< key column = "ID"/>< one-to-many class= "Student"/></set>

When the value of the inverse property of the <set> element in Group.hmb.xml is set to false, the association between group and student is maintained by group, and Group is responsible for telling student its own ID. Hibernate then sends an UPDATE statement to update the record. However, now that the value of inverse is set to true, the association between group and student is maintained by student, and the ID of group is automatically obtained by student, and the action of this student to get group ID is actually to complete a " Students added to the class "action.

The use of many-to-many association relationships

The relationship between Student (students) and course (curriculum) is a many-to-many relationship. When mapping a many-to-many relationship, you need to use a separate join table (for example, Student_course). The Student_course table consists of 2 fields: CourseID and Stuid. Also, use the <many-to-many> tag in their mapping files. Add the following description information to the student mapping file Student.hbm.xml:

<set name= "Courses" table= "Student_course" lazy= "false" inverse= "false" cascade= "Save-update" >< key column= " Stuid "/>< many-to-many class=" test. Course "column=" CourseID "/></set>

Accordingly, the course mapping file Course.hbm.xml adds the following description information:

<set name= "Students" table= "Student_course" lazy= "false" inverse= "true" cascade= "Save-update" >< key column= " CourseID "/>< many-to-many class=" test. Student "column=" Stuid "/></set>

1. Add an association relationship

Let's start by compiling a program to see what course a student named Bill has chosen:

...//Get the Student object containing Bill Student stu = (Student) session.createquery ("from Student s where s.name = ' Bill '"). Uniqueresult () ;

List ls = new ArrayList (stu.getcourses ()); for (int i=0; i<ls.size (); i++) {Course Course = (Course) ls.get (i);//Get Course Object System.out.println (Course.getname ()) ; Print bill's list of selected courses} ...

Now Bill also wants to take a business course, which for programmers just adds a business-to-business connection to Bill, which means that a new record is added to the Student_course table, and neither t_student nor t_course tables change.

...... Student stu = (Student) session.createquery ("from Student s where s.name = ' Bill '"). Uniqueresult (); Course Course = (Course) session.createquery ("from Course C where c.name = ' business '"). Uniqueresult (); Sets the relationship between Stu and Course stu.getcourses (). Add (course); Course.getstudents (). Add (Stu);...

2. Delete an association relationship

It is easier to delete an association relationship by simply invoking the Remove () method of the object collection to remove the object. For example, to remove the politics and chemistry two courses from the student bill's elective list, the procedure is as follows:

..... 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); Remove Politics course stu.getcourse (). Remove (COURSE2); Delete Chemisty course ....

Running the above statement removes the two records from the Student_course table, but the t_student and T_course tables do not change.

Hibernate manipulating objects with association relationships

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.