"Hibernate Step by Step"--bidirectional correlation one-to-one mapping (II.)

Source: Internet
Author: User

Very embarrassed, there are two days did not update the blog post, do not write the days of the article is really empty Ah, developed the habit of writing articles to change also can not be changed. Said humorous digression, two days ago received a friend's private message, invited the author to write an article about OWS, used to study the icon tool of a technology, is honored to receive the invitation of this friend, but because these days the development of the project anxious to go online so there is no time to study, can only wait this weekend, Use weekend time to study and update similar technical articles.

Back to the topic of the article, the previous article discussed the two-way primary key association, it is actually a pair of primary key association of a special case, want to achieve two-way association must be at both ends of the mapping file configuration <one-to-one>, in addition to the main map at one end of the Foreign foreign Key Association properties. Continuing the discussion of two-way correlation, there is a foreign key association in the bidirectional association that is not discussed, and the next two-way foreign Key association is discussed in detail.


two, two-way foreign key association

Two-way foreign key association can be understood as a special case of foreign Key association, this particular is because it is a bidirectional correspondence, in the previous article mentioned that if you want to add a foreign key field in a table, you can use the <many-to-one> tag, It generates the corresponding foreign key column in the relational model. The label must be used here to implement a two-way foreign key association.


1. Object Model


First look at the object model, people and identity cards belong to a one-to-one relationship, a person corresponds to an identity, so the multiplicity between them is a single, and this correspondence is bidirectional. So its object model is the same as the two-way primary key one-to-one, such as:


2. Relational Model

The corresponding relationship model will change greatly, a one-to-two foreign key association will generate a corresponding foreign key in a table, to get people and ID card, that is, the human relationship model will have a primary key column of the ID number, they form a bi-directional one-in-one situation, such as:


The correspondence between them is seen in, the person table has the Idcard table of the primary key, forming a one-to-one foreign key association, and is bidirectional, that is, through person can get to idcard, in addition through Idcard can also get to person.

The code in the Person object and the Idcard object is consistent with the object code in the previous article, not the code listing, the only difference is the configuration problem in the mapping file.


3. mapping Files


The IdCard.hbm.xml mapping file, the Idcard table is not the primary table of the map, so you need to use the <one-to-one> tag to configure the one-on mapping, and you need to develop the foreign key attributes in the person relationship model, with the following code:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Generated 2014-5-18 22:27:43 by Hibernate Tools 3.4.0.CR1-->< hibernate-mapping>    <class name= "Com.src.hibernate.IdCard" table= "Idcard" >        <id name= "id" type= " int ">            <generator class=" native "/>        </id>        <property name=" Cardno "type=" Java.lang.String ">            <column name=" Cardno "/>        </property>                <one-to-one name=" Person " property-ref= "Idcard" ></one-to-one>    </class>

Person.hbm.xml the map file, the person table is the primary table of the map, and you need to add a foreign key attribute column to the table to mark the Idcard table, so you need to use the <many-to-one> tag to generate the corresponding foreign key in the person object. and also use unique to indicate that the attribute is unique.

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Generated 2014-5-18 22:27:43 by Hibernate Tools 3.4.0.CR1-->< hibernate-mapping>    <class name= "Com.src.hibernate.Person" table= "person" >        <id name= "id" type= " int "column=" personId ">            <generator class=" native "/>        </id>        <property name=" name "type = "Java.lang.String" >            <column name= "name"/>        </property>                <many-to-one name= "Idcard" Column= "Idcardno" unique= "true" not-null= "true" ></many-to-one>    </class>

The mapping file configuration for the object is complete, and then the relational model is generated, and the SQL statements are as follows:

ALTER TABLE person drop FOREIGN key Fk8c768f55794a52cadrop table if exists idcarddrop table if exists personcreate table I  Dcard (ID integer NOT NULL auto_increment, Cardno varchar (255), primary key (ID)) The CREATE Table person (PersonId integer not Null auto_increment, NAME varchar (255), Idcardno integer NOT null unique, primary key (PERSONID)) ALTER TABLE person add I Ndex FK8C768F55794A52CA (IDCARDNO), add constraint FK8C768F55794A52CA foreign key (Idcardno) references Idcard (ID)

The resulting SQL statement is the first table created, with the primary key column specified when the table was created, and two tables were modified after creation to specify the foreign key properties to form a one-to-one relationship.

Write test methods, use unit tests, load objects of two classes, and get another object from one end of the object, respectively

Loads the object, uses the Idcard object to load the person object public void TestLoad1 () {Session session=null;try{session=hibernateutils.getsession (); Session.begintransaction ();//Gets the Idcard object, in Idcard, gets the person object that is uniquely associated with the object Idcard idcard= (idcard) session.load ( idcard.class,1); System.out.println ("person. Id= "+idcard.getperson (). GetId ()); System.out.println ("Idcard.person.name=" +idcard.getperson (). GetName ());//Gets the person object, Gets the Idcard object that is uniquely associated with it in the person object, person person=, Session.load (person.class,1); System.out.println ("Idcard.id:" +person.getidcard (). GetId ()); System.out.println ("Idcard.cardno:" +person.getidcard (). Getcardno ());//COMMIT Transaction session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}

What's generated:




Comparing two mapping relationships, primary key and foreign key mapping, both are bidirectional mapping, need to configure the mapping relationship at both ends of the object, the difference is that the primary key only need to use <one-to-one> because it does not need to generate attribute columns, However, the primary key of the table must be generated using the foreign primary key generation strategy, and the foreign key object is marked, and the foreign key generation strategy requires the <many-to-one> tag to generate a new foreign key column.


Conclusion

Two-way association in a one-to-one mapping has been discussed so far, both articles mainly discuss two ways of the use of correlation, in fact, it is very simple, remember that you want to create a foreign key to use the <many-to-one> tag, if the only way to add a unique attribute,< The one-to-one> tag simply refers to a one-to-one relationship. It just indicates how an object loads another object and does not add new columns in the relational model. The next article will discuss a one-to-many association.

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.