I. Overview
We introduce the method of mapping one-to-one correlation relation with company and address class as an example.
There are two types of correlation methods
-Follow foreign key mappings: Two tables any one of the tables defines a foreign key to associate with another table.
-Follow the primary key mapping: The primary key of one table is used as the foreign key, and the primary key of the other table is consistent.
second, according to the foreign key mapping
(1) Create an entity class
public class Company {private Integer ID; private String name; private address address; Public Integer GetId () {return id; } public void SetId (Integer id) {this.id = ID; } public String GetName () {return name; } public void SetName (String name) {this.name = name; } public Address getaddress () {return address; } public void Setaddress (address address) {this.address = address; }} public class Address {private Integer ID; private String name; Private company Company; Public Integer GetId () {return id; } public void SetId (Integer id) {this.id = ID; } public String GetName () {return name; } public void SetName (String name) {this.name = name; Getcompany () {return company; public void Setcompany, company company, {this.company = company; } }
(2) We configure the mapping file, we set the foreign key on the company side to associate an address with a foreign key to use <
Company.hbm.xml Test:
public class Demo {private session session; @Test public void Test () {//Read configuration file config Conf=ne W Configuration (). Configure (); Create Factory Sessionfactory Sessionfactory=conf.buildsessionfactory () based on configuration; Session = Sessionfactory.opensession (); Transaction ts=session.begintransaction (); Company C=new Company (); C.setname ("Baidu"); Address A=new address (); A.setname ("Shenzhen"); C.setaddress (a); A.setcompany (c); Session.save (a); Session.save (c); Ts.commit (); Session.close (); Sessionfactory.close (); }By default, a one-to-one association uses an urgent left OUTER join retrieval strategy.
Third, follow the primary key mapping The entity class does not change, we write the ID field of the table of the configuration file address is both the primary key and the foreign key. Writing configuration files Company.hbm.xml
(10) Hibernate's one-to-one relationship