Hibernate學習筆記_07_一對一雙向外部索引鍵關聯

來源:互聯網
上載者:User

設定一對一雙向外部索引鍵關聯關係,通過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必設。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.