Reprinted in Hibernate to achieve complex data mapping
Chen Yaqiang (cyqcims@mail.tsinghua.edu.cn)
Senior Software Engineer
October 2003
In the previous article, "Use Hibernate to operate the lasting object", introduce the basic concept of Hibernate, and then demonstrate how to use Hibernate in a web application to encapsulate persistent data objects. However, in a realistic project, we often need to operate multiple data sheets, and there are often complex relationships between multiple tables. In this article, how to describe how many tables in Hibernate, and how to do relation Complex persistent object. You need the following knowledge and tools before reading this article:
Tomcat 5.09, you can download from http://www.apache.org/ download; Hibernate 2.0 related running environments, you can download from http://hibernate.bluemars.net/; at least one database server is installed and related JDBC drivers program. Reference information in this article
All code from this article download here
Case introduction
In the first article, we have a simple package for a table. In this article, we discuss more complex situations.
In this example, a one-to-one, one-to-many, multi-to-many cases are considered. As shown in Figure 1.
Figure 1 mapping relationship between the entity
In the above data model diagram, Student is the core of all tables, it and the CLASSES table are a pair of relationships, and the course table is a multi-to-many relationship (link through the student_course_link table), and the address table is one-on-one Relationship.
Through analysis, we can convert the above data model into the following Java persistent object, as shown in Figure 2.
Figure 2 relationship between persistent objects
It can be seen that the data model diagram and the class diagram of the Java persistent object have a very similarity, but it is not exactly the same. For example, the Classes table and the Student table are a couple of relationships; in the class diagram, both are still a couple of relationships, but add a Student property in the CLASSES class. The type of attribute is java.util.set, it Represents all STUDENT objects included in the Classes object.
Create a Hibernate persistent object
The data model has been analyzed, and the lasting object can now be created. The relationship between the persistent object is specified by the class diagram shown in Figure 2.
Let's take a look at the Student class, which is the core of this relationship map, and the code is as shown in routine 1.
Routine 1 Student lasting object (student.java)
Package com.hellking.study.hibernate;
Import java.util.set; / *** represents the class of the Students table in Hibernate. * / public class student {/ ** property, and the field in the Students table corresponds to the ** / private string id; private string name; / ** and other mappings ** / private set coursetes; private classes classes Private address address; / ** Access method must be a public method ** / public void setid (String String) {id = string;} public string getId () {return ID;} public void setname (String Name ) {this.name = name;} public string getname () {return this.name;} / ** relationship between operation and other objects ** / public void setCourses (SET CO) {this.courses = CO; public Set getCourses () {return this.courses;} public void setAddress (address ad) {this.address = address;} public address getAddress () {return this.address;} public void setClasses (Classes c) {this.classes = C;} public classes getClasses () {return this.classes;}} In the Student class, because the table of the Students table and Classes is multi-to-one relationship, it contains a Classes property that type Classes, which The actual significance is that a student can have a class; the table of Students and Address is a one-on-one relationship, which also contains a type of address attribute. Its actual meaning is an address; Students Table and Course It is a multi-to-many relationship, so it contains a COURSE attribute of java.util.set. Its actual significance is that a student can learn a multi-dochi, and a course can be repaired by multiple students.
Classes objects and Student objects are a pair of relationships. The Classes object contains a STUDENTS property that is java.util.set, which is shown in routine 2.
Routines 2 Classes lasting objects (Classes.java)
Package com.hellking.study.hibernate;
Import java.util.set; / *** Represents classes of the classs table in Hibernate. * / public class classes {/ ** property, and the field of the class of the class ** / private string id; private string name; / ** and other classes ** / private set students; / ** Property The access method must be a public method ** / public void setid (String String) {id = string;} public string getId () {returnid;} public void setname (String name) {this.name = name;} Public string getName () {return this.name;} / ** relationship between operation and other objects ** / public void setstudents (SET STUD) {this.students = stud;} public set getstudents () {Return THIS. STURENTS;}} Course lasting object In the previous article, it has been introduced, and it will not be listed here. The Address persistent object is relatively simple. In addition to the properties defined by the table field, it is not introduced into the code in this article.
Describe the relationship between objects
Now we have written a long-lasting object, the following tasks are to describe the relationships between them. First we look at the description of the Student persistent object, as shown in routine 3.
Routine 3 Student's Description (Studient.hbm.xml)
XML Version = "1.0"?>
To describe, the name here is an attribute that the name address in the Student object; the class represents the type of Address property: com.hellking.study.hibernate.Address.
Next, look at many-to-one relationship between Student and Classes, use:
To describe it. Similarly, Name is indicated by the attribute of the name Classes in the Student object; the class represents the type of the classes property, and the column represents the external key name used by the Student table references the CLASSES table. Correspondingly, the Student class is also referenced in the CLASSES class, which uses the following descriptors to describe this relationship:
When describing multiple-to-many relationships between Student and Course, the following methods are used:
Specifies the external key of the Student object in the Student_Course_LINK link table. Correspondingly, the following descriptors are used in the Course persistent object to describe this relationship:
Since the description of other persistent objects is basically, it will be listed here, please refer to the source code of this article. Don't forget to add a description of these objects in hibernate.cfg.xml.
Use mapping relationship Below we develop a simple instance to test this mapping. The most frequent operation of persistent objects is to increase data, query data, delete data, and update data. For updating data, the operation of multiple tables and individual tables are not different, and it is not exemplified here. Add data to the database We are here to test the first three operations, first to see the case where data to the database, as shown in routine 4. Routine 4 Test the image of mapping between persistent objects (some code of maptestBean.java) / *** Add data in the database * / public void adddata (String StudentID, String Classesi, String CourseSid) throws hibernateException {try {/ *** The following code adds a Student, specified for Student * Address, Courses And classses. * / beginTransAction (); // Create a Student object. Student Student = New Student (); Student.setName ("Hellking2"); Student.SetId (studentId); // Create an Address object. AddR = new address (); addr.setcity ("beijing"); addr.setState ("bj"); addr.setstreet ("tsinghua); addr.setzip (" 100083 "); addr.setId (student. GetId ()); // Set the relationship between STUDENT and ADDRESS. Student.Setaddress (AddR); set set = new hashset (); set.add (student); // Create a Course object. Course course = new course (); course.setId; course.setname ("Computer_JSP"); // Setting the relationship between Course and Student objects. Course.setStudents (SET); // Create a CLASSES object. Classes cl = new class (); cl.setId; cl.setname ("Engine Power"); // Sets a STUDENTS object included in a CLASSES object. Cl.setStudents (SET); // Due to the two-way relationship, the Student object also needs to be set once. Student.setClasses (CL); // Save the created object into the session. Session.save (Cl); session.save (course); session.save (student); session.save (addr); // Submit transaction to make changes to take effect. EndTransaction (TRUE);} catch (hibernateException e) {system.out.println ("When data is added!"); E.PrintStackTrace (); throw e;}} In routine 4, add data to the database First, set various properties of the lasting object, such as: Student.setName ("Hellking2"); This way of setting attributes and normal classes have no difference. After setting all the properties, set the relationship between persistent objects, such as: Student.Setaddress (AddR); If there is a multiple relationship between objects, you may need to save the object in the set collection and then set, such as: Set set = new hashset (); set.add (student); course.setstudents (SET); When all the properties and object relationships are set, you can call: Session.save (PersistentObject); The method is saved to the Hibernate session. Finally, call EndTransaction to submit transactions and turn off the Hibernate session. data query In complex entity object mapping, it is often queried more complicated. As a demonstration, we also provide several query methods, as shown in routine 5. Routine 5 Test the query data of mapping between persistent objects (some code of MapTestBean.java) / *** Student obtain a given studentid address information * / public Address getAddress (String id) throws HibernateException {beginTransaction (); Student st = (Student) session.load (Student.class, id); Address addr = (Address) session.load (address.class, st.getid ()); endtransaction (false); returnadr;} / *** Get all courses for a given StudentID * / public set getCourses (String ID) THROWS HibernateException {begintransAction (); Student St = (student) session.load (student.class, id); endtransaction (false); return st.getCourses ();} / *** Test Get a given StudentID Classes of Student belongs * / public Classes getClasses (String id) throws HibernateException {beginTransaction (); Student st = (Student) session.load (Student.class, id); System.out.println (st.getClasses (). GetId ()); endtransaction (false); return st.getClasses (); Here is three kinds of query methods, namely: Query the STUDISS information of the given ID; all COURSES information for the STURSS for a given ID; query the class content of the STUDENT of the given ID. In the query, first create a Hibernate session object using the Begintractions () method and start a new Hibernate transaction; then get a STUDENT object for a given ID through the session.Load () method, such as: Student ST = (student) session.load (student.class, id); Finally call the Student.Getxxx () method to return to the specified object. delete data When the relationship between the table is more complicated, to delete data, there is often a case where the cascade deletion is exist, and the case is more complicated because the level of the cascade is more complicated, and it is not exemplary here. Suppose we want to delete all related records of the Student object of a given ID, you can use the methods shown in routine 6. Routine 6 Test Delete Data (MapTestBean.java section) / *** Delete all information related to a student * (here is just testing, we don't talk about this operation). * / Public void delteStudent (String id) throws HibernateException {beginTransaction (); Student st = (Student) session.load (Student.class, id); Address addr = (Address) session.load (Address.class, st.getId ()); // Delete Address information. Session.Delete (addr); // Delete the classes information. Session.delete (st.getClasses ()); / *** Delete Course one by one. * / for (iTerator it = st.getcourses (). Iterator (); it.hasnext ();) {course c = (course) it.next (); session.delete (c);} // final, delete Student object. SESSION.DELETE (ST); ENDTRANSACTION (TRUE);} Again .delete () method to delete the specified object. If you want to delete an object in a collection, you can delete one by one, such as the method of deleting Courses in routine 6. test Here is a program for tested MapTestBean in JSP, see maptest.jsp files. Before performing tests, make sure that the connection database is complete, and there is no error in each persistent object. If the configuration is difficult, please refer to the source code of this article. let's move After two articles learned from shallow to profound, I hope to play the role of pouring bricks, I believe that readers have a holistic grasp of Hibernate. Hibernate is gradually widely used in enterprise application development due to its ease of use and good graft. Hibernate official website provides a very good manual, you can refer to it. If you are not proficient in JDBC and don't want to learn it, consider using hibernate; if you have difficulty in using the persistent framework like entity beans, maybe Hibernate can help you! Reference The source code of this article is downloaded here. Http://www.apache.org/ Download Tomcat. Hibernate's official website, http://hibernate.bluemars.Net/, contains the latest information on Hibernate. Hibernate Chinese Forum, hibernate.fankai.com contains more than Hibernate. Contains Hibernate technology discussion site, http://www.jdon.com/, warm discussion in Hibernate, JDO, CMP, etc. = 6062 & start = 0 & msRange = 15 in lively discussion Hibernate, JDO, CMP and other technology 2: http:? //www.theserverside.com/discussion/thread.jsp thread_id = 19732Hibernate2 Reference Documentation, Hibernate can be obtained from the official website, very good References. Hibernate In Action, a very professional Hibernate reference book, the main developer of the Hibernate project, GAVIN KING, MANNING Publishing House. You can get some chapters of this book from http:// http://www.theserverside.com. About author Chen Yaqiang: Beijing Huayuan Tianyi Technology Co., Ltd. Senior software engineer, good at J2EE technology, participated in the design and development of multiple J2EE projects, has great interest in web services and has certain project experience. Love to learn, like new technologies, have participated in the writing of many books. Helloger friends, you can contact him via cyqcims@mail.tsinghua.edu.cn.