hibernate4之一對多關聯性映射(三)

來源:互聯網
上載者:User

標籤:hibernate4之一對多關聯性映射

樣本:一個部門(Department )下面有多個使用者(User),多個使用者對應一個部門

public class Department {    private Integer id;    private String name;    private Set<User> users;        //getter and setter  }
public class User{    private Integer id;    private String userName;    private Department department;        //getter and setter  }

用XML映射

<hibernate-mapping package="com.shen.hibernate4.entity">    <class name="Department " table="tb_department ">        <id name="id">            <generator class="identity" />        </id>        <property name="name" />       <!--反轉:設定從User端加入資料失效,不維護關聯關係。注:Hibernate預設inverse="false"為主控方,由主控方負責維護對象的關係聯絡。-->        <set name="users" inverse="true">              <key column="department_id" />              <one-to-many class="User"/>        </set>      </class></hibernate-mapping> <hibernate-mapping package="com.shen.hibernate4.entity">    <class name="User" table="tb_user">        <id name="id">            <generator class="identity"/>        </id>        <property name="userName" column="user_name"/>         <!-- 此處需要與Department 端的配置的欄位保持一致-->          <many-to-one name="department" column="department_id" class="Department " not-null="true"/>    </class></hibernate-mapping>


用@Annotation映射

@Entity@Table(name = "tb_department")public class Category {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Integer id;    private String name;        //mappedBy 值為User中Department類型屬性    @OneToMany(mappedBy = "department")    private Set<User> users;    //getter and setter }
@Entity@Table(name = "tb_user")public class User{    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Integer id;    private String userName;        @ManyToOne      @JoinColumn(name = "department_id", nullable = false)    private Department department;        //getter and setter  }





本文出自 “冰葫蘆” 部落格,請務必保留此出處http://shenlang7.blog.51cto.com/3102414/1742804

hibernate4之一對多關聯性映射(三)

聯繫我們

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