首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate 利用 XDoclet 自動產生映射檔:多對多關聯完整範例

     編輯:Java 相關知識

以 Position 與 User 多對多關聯(中間表 test_user_position)為例,示範在 POJO 加入 XDoclet 標籤,經 MyEclipse 執行 XDoclet 自動產生 .hbm.xml。

POJO 標籤範例

/** @hibernate.class table="test_position" */
public class Position {
    private int id;
    private String name;
    private Set users = new TreeSet<>();

    /** @hibernate.id generator-class="identity" type="int" */
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    /** @hibernate.property length="25" */
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    /** @hibernate.set inverse="true" lazy="true" table="test_user_position"
     *  @hibernate.collection-key column="position_id"
     *  @hibernate.collection-many-to-many class="test.User" column="user_id" */
    public Set getUsers() { return users; }
    public void setUsers(Set users) { this.users = users; }
}

/** @hibernate.class table="test_user" */
public class User {
    private int id;
    private String name;
    private Set positions = new TreeSet<>();

    /** @hibernate.id generator-class="identity" type="int" */
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    /** @hibernate.property length="25" */
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    /** @hibernate.set table="test_user_position" lazy="true"
     *  @hibernate.collection-key column="user_id"
     *  @hibernate.collection-many-to-many class="test.Position" column="position_id" */
    public Set getPositions() { return positions; }
    public void setPositions(Set positions) { this.positions = positions; }
}

MyEclipse 設定步驟

  1. 專案右鍵 → Properties → MyEclipse/XDoclet → Add Standard → 選「Standard Hibernate」。
  2. 建立 Hibernate.cfg.xml 設定 SessionFactory 與資料源。
  3. 專案右鍵 → MyEclipse/Run XDoclet → 自動產生兩個 .hbm.xml。

產出檔案修正

產生的 hbm 中會出現多餘的 role 與 readonly 屬性,需手動將 role 改為 name,移除 readonly 後方可正常使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved