您的位置:首页 > 其它

hibernate关系映射

2016-01-12 01:17 204 查看
多对一

<!--
映射多对一的关联关系。 使用 many-to-one 来映射多对一的关联关系
name: 多这一端关联的一那一端的属性的名字
class: 一那一端的属性对应的类名
column: 一那一端在多的一端对应的数据表中的外键的名字
-->
<many-to-one name="teacher" class="Teacher" column="teacherId"/>


一对多

<set name="orders" table="t_order" inverse="true" cascade="save-update" order-by="order_name desc">
<key column="customer_id"></key>
<one-to-many class="Order"></one-to-many>
</set>


一对一外键关联(添加外键的表用many-to-one标记,不添加外键的表使用one-to-one)

<many-to-one name="manager" class="Manager" column="manager_id" unique="true"></many-to-one>

<one-to-one name="department" class="Department" property-ref="manager"></one-to-one>


一对一主键关联映射

idcard生成主键,person依赖于idcard的主键.所以person的主键生成方式使用foreign

<class name="IdCard" table="idcard">

<id name="id" type="java.lang.Integer">
<column name="ID"/>
<generator class="native"/>
</id>

<property name="cardNo"/>
<one-to-one name="person" class="Person"></one-to-one>
</class>


<class name="Person" table="person">

<id name="id" type="java.lang.Integer">
<column name="ID"/>
<generator class="foreign">
<param name="property">idCard</param>
</generator>
</id>

<property name="name"/>
<one-to-one name="idCard" class="IdCard" constrained="true"/>
</class>


多对多映射(多对多一定要设置主控端)

<!-- table: 指定中间表 key:表示使用的列名来对应该表的主键 -->
<set name="items" table="CATEGORIES_ITEMS">
<key>
<column name="C_ID" />
</key>
<!-- 使用 many-to-many 指定多对多的关联关系. column 执行 Set 集合中的持久化类在中间表的外键列的名称  -->
<many-to-many class="Item" column="I_ID"></many-to-many>
</set>


<set name="categories" table="CATEGORIES_ITEMS" inverse="true">
<key column="I_ID"></key>
<many-to-many class="Category" column="C_ID"></many-to-many>
</set>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: