hibernate 實體關聯映射筆記

來源:互聯網
上載者:User

標籤:style   java   tar   get   使用   資料   

@常用屬性說明:
    @Entity:實體類
    @Table:指定對應資料表
    @Id:主鍵,使用可以為null值的類型,如果實體類沒有儲存到資料庫是一個臨時狀態
    @Column:配置普通屬性,除了主鍵外,java基本類型的屬性
    @Base:普通屬性的載入方式
    @GeneratedValue:主鍵建置原則
    @Temporal:日期類型(DATE,TIME還是TIMESTAMP),如果屬性類型是java.util.Date(是以上3個類的父類)類型時才需要使用該@聲明具體的日期類型
    @Transient:臨時屬性
    @Version:版本屬性,配置樂觀鎖

hibernate實體關聯映射:
    一對一單向:
        一段:另一端實體屬性:@OneToOne(cascade),@JoinColumn(name=外鍵名,unique=true)
        另一端:
        一段資料庫:另一端實體的外鍵:表名_id
        另一端資料庫:
    一對一雙向:
        一段:另一端實體屬性:@OneToOne(cascade),@JoinColumn(name=外鍵名,unique=true)
        另一端:另一端實體屬性:@OneToOne(mappedBy=另一端屬性名稱)
        一段資料庫:另一端實體的外鍵:表名_id
        另一端資料庫:
    一對一雙向(主鍵):
        一段:@Id,@GeneratedValue,另一端實體屬性:@OneToOne,@PrimaryKeyJoinColumn
        另一端:@Id,不能使用@GeneratedValue(與另一端使用相同主鍵),另一端實體屬性:@OneToOne,@PrimaryKeyJoinColumn
        一段資料庫:沒有關聯,根據主鍵判斷
        另一端資料庫:沒有關聯,根據主鍵判斷
    一對多單向:
        一段:多端實體集合屬性:@OneToMany(fetch,cascade,targetEntity(使用範型可以省略)),@JoinColumns(value={@JoinColumn(name="外鍵名"),referencedColumnName="另一端id"})
        多端:
        一段資料庫:
        多端資料庫:一段實體的外鍵:表名_id
    多對一單向:
        一段:
        多端:一段實體屬性:@ManyToOne(CascadeType,fetch),@JoinColumn(外鍵名)
        一段資料庫:
        多端資料庫:一段實體的外鍵:表名_id
    一對多雙向(多對一雙向):
        一段:多端實體集合屬性:@OneToMany(mappedBy="多端實體類中的一段屬性名稱")
        多端:一段實體屬性:@ManyToOne(fetch,cascadeType),@JoinColumn(外鍵名)
        一段資料庫:
        多端資料庫:一段實體的外鍵:表名_id
    多對多單向:
        多段:另一端實體集合屬性:@ManyToMany(fetch,cascade,),@JoinTable(name,JoinColumns,inverseJoinColumns)
        另一多端:
        多段資料庫:
        另一端端資料庫:
        中間表(表1_表2):外鍵1:表1_id,外鍵2:表2_id
    多對多雙向:
        多段:另一端實體集合屬性:@ManyToMany(fetch,cascade,),@JoinTable(name,JoinColumns,inverseJoinColumns)
        另一多端:@ManyToMany(mappedBy=另一多端實體集合屬性名稱)
        多段資料庫:
        另一端端資料庫:
        中間表(表1_表2):外鍵1:表1_id,外鍵2:表2_id


1 雙邊關係中,控制權一般交給多端,由mappedBy指定,配置資訊要到多端找
2 mappedBy把控制權交給另一端(另一端中的屬性名稱),另一端配置同單向配置完全相同
3 多對多屬性必須使用@JoinTable指定中間表的配置,其中name指定表名,joinColumns指定該表與中間表的對應關係,inverseJoinColumns指定另一端與中間表的關係
4 mappedBy表示該屬性是反向屬性,與另一端實體類的指定的屬性對應
5 Map映射:集合屬性可以使用Map類型,Map使用索引-值屬性對,速度快,配置時跟@OneToMany,@ManyToMany一樣,只需再增加@MapKey即可,如:
    @MapKey(name = "name")//設定資料庫列名,使用該欄位索引資料
    private Map<String,Student> students = new new HashSet<String,Student>();

聯繫我們

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