[Java]
One-to-one relationship: person-ID card
There is a one-to-one relationship in a relational database. This is similar to the above situation. One person corresponds to only one ID card.
And vice versa. In the object model of hibernate, how does one configure the one-to-one association ing relationship?
1. JavaBean: (the set and get methods are omitted)
1. Person. java
Private int id;
Private String name;
Private IdCard idcard;
2. IdCard. Java
Private int id;
Private String usetime;
Private Person person;
2. Xml configuration file: it is not difficult to see that the two classes have an attribute form of each other. The xml file of hibernate is as follows:
Person. hbm. xml
<Hibernate-mapping
Package = "cn. hibernate. model">
<Class name = "Person" table = "person">
<Id name = "id">
<Generator class = "native"/>
</Id>
<Property name = "name" column = "name"/>
<! -- One-to-one object relationship description -->
<One-to-one name = "idcard"/>
</Class>
</Hibernate-mapping>
IdCard. hbm. xml
<Hibernate-mapping
Package = "cn. hibernate. model">
<Class name = "IdCard" table = "idcard">
<Id name = "id">
<! -- The primary key here is also a foreign key
Because it coexist with peroson. So the primary key is configured here.
-->
<Generator class = "foreign">
<! -- Indicates where the primary key comes from. This person refers to its object property -->
<Param name = "property"> person </param>
</Generator>
</Id>
<Property name = "usetime" column = "usetime"/>
<! -- For a one-to-one relationship, you only need to use the name of the specified attribute. -->
<One-to-one name = "person" constrained = "true"> </one-to-one>
</Class>
</Hibernate-mapping>
3. Insert a table:
Static void AddPersonAndIdCard (){
Session s = null;
Transaction tx = null;
Try {
S = HibernateUtil. getSession ();
Tx = s. beginTransaction ();
Person p = new Person ();
IdCard idcard = new IdCard ();
P. setName ("zhanglei ");
Idcard. setUsetime ("usertime ");
Idcard. setPerson (p );
P. setIdcard (idcard );
S. save (p );
S. save (idcard );
Tx. commit ();
System. out. println ("1111 ");
} Catch (HibernateException e ){
// Determine whether the transaction is fully committed.
If (tx! = Null ){
Tx. rollback ();
Throw e;
}
} Finally {
If (s! = Null ){
S. close ();
}
}
}
// Note:
/*
For the Java code above, there are some custom classes. Get the session object. If you want to view the encapsulation class, read the previous BLOG
This article focuses on the setPerson operation of idcard. This operation cannot be absent. Because its ID generates the ID value dependent on person.
*/
Author: zhang6622056