Hibernate provides two ways to map one-to-one relationships: by foreign key mapping and by primary key mapping.
The following is an example of the employee account and employee Profile table, which describes the two mapping methods:
1. Follow the foreign key map
Step one : Create entity classes Users1 and Resume1
Users1 is created as follows:
Public class Users1 {
Private Integer userid;
Private String username;
Private String Userpass;
Private Resume1 resume1;
.... Slightly
}
RESUME1 is created as follows:
Public class Resume1 {
Private Integer Resid;
Private String Resname;
Private String Rescardno;
Private Users1 users1;
.... Slightly
}
Step two : Configure files Users1.hbm.xml and Resume1.hbm.xml (small configuration)
The Users1.hbm.xml configuration is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">
The Resume1.hbm.xml configuration is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">
Step three : Test method writing
public void Testadd () { Session session = Hibernateutil.getsession (); Transaction tx=session.begintransaction (); Create a User object Users1 u1=new Users1 ("Happy", "1"); Create an Archive object Resume1 r1=new Resume1 ("Primary Archives", "Happy01"); U1.SETRESUME1 (R1); R1.setusers1 (U1); Save R1 automatically save U1 Session.save (R1); Tx.commit (); System.out.println ("ok==="); }
2. Follow the primary key mapping
Step one : Create entity classes Users2 and Resume2
The USERS2 is created as follows:
Public class Users2 {
Private Integer userid;
Private String username;
Private String Userpass;
Private Resume2 resume2;
}
The Resume2 is created as follows:
Public class Resume2 {
Private Integer Resid;
Private String Resname;
Private String Rescardno;
Private Users2 users2;
}
Step two : Configure files Users1.hbm.xml and Resume1.hbm.xml (small configuration)
The Users1.hbm.xml configuration is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">
Resume2.hbm.xml Configuration
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd ">
One-to-one correlation mappings