Hibernate架構學習(三) 關係映射

來源:互聯網
上載者:User

 Hibernate中關係映射指的是實體類與實體類間的關係。和資料庫中表與表之間的關係類似,有一對一,多對一,一對多,多對多四種映射關係。

 

一:一對一映射

   兩個對象之間是一對一的關係,如人和身份證之間是一對一的關係。

   實現一對一映射有兩種方式,一種是主鍵約束,一種是外鍵約束

    1,主鍵約束

     資料庫表不會有額外的欄位維護他們之間的關係,僅通過表的主鍵來關聯

       1)物件模型

                             

      2)關聯式模式

                              

   2,外鍵約束

   在一種一個對象中加入另一個對象的屬性

    1)物件模型

                             

    2)關聯式模式

                               

   3)xml中配置

    由於IDCard 身份證實體類是被引入,它的設定檔不發生變化,Person類的設定檔中需要做相應配置,又由於在人的一段能看到卡的資訊,配置資訊時,需要注意在引入的一方使用many-to-one標籤

  

    主要:many-to-one標籤中的name屬性是IDCard對象主鍵欄位前面加上get欄位。


 

二:多對一

 多對一映射,如學生和班級之間的關係,多個學生對應一個班級。

 1, 物件模型中是在多的一方對象中加入一的一方對象的引用。設定檔參見上圖所示。

 2,註解使用

@Entitypublic class Person {private int id;private String name;private IDCard cid;@ManyToOne@JoinColumn(name="cardid")public IDCard getcid() {return cid;}

 用@JoinColumn來指定外鍵的欄位名

三:一對多

   一對多的映射,如班級和學生的關係,一個班級中有多個學生。

  1,物件模型中是在一的一端添加Set集合,包含多的一端。

   

public class Classes{private int cid ;private String cname ;private Set<Student> studentSet = new HashSet<Student>(); //一對多public int getCid() {return cid;}public void setCid(int cid) {this.cid = cid;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}public Set<Student> getStudentSet() {return studentSet;}public void setStudentSet(Set<Student> studentSet) {this.studentSet = studentSet;}}

 2,設定檔

     1)在多的一端課程,使用set標籤並使用one-to-many標籤


    2)在一的一端學生,使用many-to-one標籤


 3,註解

@OneToMany//進行註解為一對多的關係@JoinColumn(name="classesId")//在多的一端註解一個欄位(名為classessid)public Set<Student> getStudents() {return students;        }

   在set集合屬性的get方法前面使用@OneToMany註解


三:多對多

  多對多映射關係,還拿學生課程關係,多個學生對應多個課程,多個課程對應多個學生

  1,在物件模型中是雙方都加入set集合

  2,xml設定檔中,雙方也都用set標籤和many-to-many標籤

  3,註解

     @ManyToMany    @JoinTable(name="t_s_c",//使用@JoinTable標籤的name屬性註解第三方表名稱joinColumns={@JoinColumn(name="courseId")},     //使用joinColumns屬性來註解當前實體類在第三方表中的欄位名稱並指向該對象inverseJoinColumns={@JoinColumn(name="studentId")}    //使用inverseJoinColumns屬性來註解當前實體類持有引用對象在第三方表中的欄位名稱並指向被引用對象表)public Set<Student> getStudents() {return Students;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.