Hibernate--使用註解配置映射關係,hibernate--註解

來源:互聯網
上載者:User

Hibernate--使用註解配置映射關係,hibernate--註解

寫在前面:

  配置實體類與資料庫的映射關係,有兩種方式:

  1.使用*.hbm.xml    ;   

   2.使用@註解

 

一:註解的方式:

  1.@Entity

    加在類的前面,將類聲明為持久化類。

  2.@Table

    加在類的前面,為類聲明關聯的表名。如果表名和類名相同,可以省略。

       eg:@Table(name="tbl_role") 

  

    3.@Proxy

    加在類的前面,修改類級的引索策略,預設是消極式載入 可以不寫

       eg: @Proxy(lazy=false)   //改為立即載入

  

  4.@ID

       加在主鍵的get/set方法前面前面,或者加在屬性前面,補充屬性:

      @GeneratedValue -主鍵自增策略,

                 @GeneratedValue(Strategy=GenerationType.Auto),預設是Auto

     一般與@GenericGenerator一起使用:

    eg:  @GenaratedValue(generator="native_name")

      @GenericGenerator(name="native_name",strategy="native") //主鍵建置原則為native

    注意generator的值跟name中的值一致

     

                

  5.@Column 

     如果屬性名稱和對應的資料庫表列名不同, 或者get/set方法對應的屬性名稱不是列名, 需要加在get/set方法前面,或者加在屬性前面

      eg:@Column(name = "RoleName")

 

  關聯關係:

===

  6.@ManyToOne--------多對一(外鍵)關聯關係

        eg:@ManyToOne(targetEntity=class_name.class) 

        @JoinColumn(name="c_name")    //多對一對應的外鍵列名

 

 

   7.@OneToMany --------一對多關聯屬性

             eg: @OneToMany(targetEntity=class_name.class,mappedBy="property_name",cascade={CascadeType.ALL})     

             如果Set沒有加泛型,需要加targetEntity mappedBy是targetEntity中相關聯的屬性,並由它來維持外鍵關係

 

        8.@ManyToMany -多對多      

    eg:@ManyToMany(targetEntity = Function.class)

         @JoinTable(name = "role_function_r", joinColumns = @JoinColumn(name = "roleId"),inverseJoinColumns=@JoinColumn(name="functionId"))

    圖中(1)表示多對多關係的中間表的表名,(2)表示中間表與本實體類表的外鍵關係,(3)表示中間表與另一個張表的外鍵關係

 

===

  9.@Transcient

    加在get/set方法前面,或者加在屬性前面,聲明該屬性不需要被持久化

 

  

聯繫我們

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