Hibernate學習筆記_06_一對一單向外部索引鍵關聯

來源:互聯網
上載者:User

設定一對一的單向外部索引鍵關聯關係,通過Husband可以找到Wife,但是不能通過Wife找到Husband

1、編寫實體類Wife;

       使用Annotation時,將實體類進行註解,@Entity 、@Id

package com.hibernate._0600_one2one_uni_fk;import javax.persistence.Entity;import javax.persistence.Id;@Entitypublic class Wife {private Integer id;private String name;@Idpublic 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;}}

2、編寫Husband類,並在Husband中添加Wife的引用 ;

package com.hibernate._0600_one2one_uni_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")            //@JoinColumn 串連的欄位,指定資料庫中的名字,預設為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;}}

     在HUsband中添加Wife的引用,引用Wife的id ;

    使用Annotation時,將實體類進行註解,@Entity 、@Id;

    同時添加註解,設定關聯關係為@OneToOne ;

    @JoinColumn註解可以設定外鍵在資料庫中的欄位名,也可以指定長度、類型等;


3、編寫測試類別,產生資料庫表,查看錶的關係;

public class ORMTest{private static SessionFactory sessionFactory;@BeforeClasspublic static void beforeClass() {sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();}@AfterClasspublic static void afterClass() {sessionFactory.close();}@Testpublic void testSchemaExport() {new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);    }}

4、在xml檔案中,在class標籤中加入
     <many-to-one name="wife" column="wifeId" unique="true"></many-to-one>

     unique="ture"  約束成一對一關聯;

聯繫我們

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