設定一對一雙向外部索引鍵關聯關係,通過Husband可以找到Wife,也能通過Wife找到Husband
1、編寫Husband類,並在Husband中添加Wife的引用 ;
使用Annotation時,將實體類進行註解,@Entity 、@Id;同時添加註解,設定關聯關係為@OneToOne ;
package com.hibernate._0700_one2one_bi_fk;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.OneToOne;/**雙向一對一外間關聯,*/@Entitypublic class Husband {private Integer id;private String name;private Wife wife; //去參考wife的id,此時wife必須先id@Id@GeneratedValuepublic Integer getId() {return id;}public String getName() {return name;}@OneToOne //設定關聯關係@JoinColumn(name="wifeId") //指定資料庫中的名字,預設為wife_idpublic Wife getWife() {return wife;}public void setId(Integer id) {this.id = id;}public void setName(String name) {this.name = name;}public void setWife(Wife wife) {this.wife = wife;}}
2、編寫實體類Wife,並在Wife中引用Husband;
package com.hibernate._0700_one2one_bi_fk;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.OneToOne;@Entitypublic class Wife {private Integer id;private String name;private Husband husband;/** mappedBy="wife"中的這個wife是Husband中的wife屬性,表示Husband起主導作用如果不加,在資料庫中Wife表中會產生husband_id這個冗餘欄位*/@OneToOne(mappedBy="wife") public Husband getHusband() {return husband;}@Idpublic Integer getId() {return id;}public String getName() {return name;}public void setHusband(Husband husband) {this.husband = husband;}public void setId(Integer id) {this.id = id;}public void setName(String name) {this.name = name;}}
使用Annotation時,將實體類進行註解,@Entity 、@Id;
同時也設定設定關聯關係為@OneToOne,但是此時要加上屬性mappedBy屬性,
mappedBy="wife"中的這個wife是Husband中的wife屬性,表示Husband起主導作用。
如果不加,在資料庫中Wife表中會產生husband_id這個冗餘欄位;
3、編寫測試類別,產生資料庫表,查看錶的關係;
4、在xml檔案中,在class標籤中設定關聯關係。
在Husband.hbm.xml 設定檔中介入
<many-to-one name="wife" column="wifeId" unique="true"></many-to-one>
unique="ture" 約束成一對一關聯;
在Wife.hbm.xml 中添加
<one-to-one name="husband" property-ref="wife"></one-to-one>
property-ref指的是與之關聯的類Husband中的屬性wife。
5、總結:
凡是雙向關聯,mappedBy必設。