使用Hibernate Annotations

來源:互聯網
上載者:User

標籤:hibernate

這篇post承接上一篇,用來說明如何使用註解替代映射xml檔案。使用註解會很方便,減少了中繼資料的行數,並且註解是型別安全的。如果註解就是你想從JPA中獲得的唯一東西——即用註解取代XML,那麼只需要進行如下改動:

主要的變動如下:


1.需要另外匯入的包

hibernate/lib/jpa/

hibernate/lib/jpa-metamodel-generator/

裡面的兩個jar檔案,用來支援註解映射


2.刪掉映射xml檔案,即Message.hbm.xml檔案


3.使用註解映射Message類

package test.domainwithannotation;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;@Entitypublic class Message {@Id @GeneratedValue@Column(name="MESSAGE_ID")private Long id;@Column(name="MESSAGE_TEXT")private String text;@ManyToOne(cascade=CascadeType.ALL)@JoinColumn(name="NEXT_MESSAGE_ID")private Message nextMessage;public Message(){}public Message(String text){this.text = text;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getText() {return text;}public void setText(String text) {this.text = text;}public Message getNextMessage() {return nextMessage;}public void setNextMessage(Message nextMessage) {this.nextMessage = nextMessage;}}

4.更改hibernate.cfg.xml檔案中

將<mapping resource="test/domain/Message.hbm.xml" />

改為<mapping class="hello.Message" />

聯繫我們

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