4.Hibernate组件映射

  1. 所谓组件映射即为当一个实体类中有一个属性为自定义的类,但又没有oid,即数据库中没有这个类的对应表。也称这种属性为值对角或实体类的组件。如User类中有一个Contact的引用,而引用中包含各种联系信息。要把这个组件的信息一起存入User对应的表中。这样的好处是可以对Contact进行重复利用等。

映射方式:

<class name="User" table="tb_User">

<id name="id" column="id">

<generator class="increment"/>

</id>

<property name="userName" column="userName" unique="true" not-null="true"/>

<property name="sex" column="sex" />

<property name="birthday" column="birthday"/>

<component name="contact">

<property name="zcode" column="zcode"/>

<property name="email" column="email"/>

<property name="telephone" column="telephone"/>

<property name="mobilePhone" column="mobilePhone"/>

<property name="address" column="address"/>

</component>

</class>

复合主键映射

  1. 所谓复合主键,即为几个字段组合为表的主键

这种使用方式并不推荐

复合主键为一个实现序列化的实体类。如下

package edu.yzu.entity;

import java.io.Serializable;

@SuppressWarnings("serial")

public class Scpk implements Serializable {

    private Integer stId;

    private Integer coId;

    public Integer getStId() {

       return stId;

    }

    public void setStId(Integer stId) {

       this.stId = stId;

    }

    public Integer getCoId() {

       return coId;

    }

    public void setCoId(Integer coId) {

       this.coId = coId;

    }

}

 

下面为学生选课表对应的实体类

package edu.yzu.entity;

 

public class Student_Course {

private Scpk scpk;

 

public Scpk getScpk() {

    return scpk;

}

 

public void setScpk(Scpk scpk) {

    this.scpk = scpk;

}

 

}

下面为中间表的映射。事实上联合主键一般用来解决多对多的问题,配置如下。

<class name="Student" table="tb_Student">

<id name="id" column="id">

<generator class="increment"/>

</id>

<property name="name" column="name"/>

<property name="age" column="age"/>

<property name="sex" column="sex"/>

<set name="courses" table="tb_sc">

<key column="stid"/>

<many-to-many class="Course" column="coid"/>

</set>

</class>

 

<class name="Course" table="tb_Course">

<id name="id" column="id">

<generator class="increment"/>

</id>

<property name="name" column="name"/>

<property name="shall" column="shall"/>

<!-- 这里的inverse="true" 表示第三方表由其另外一使用方来维护,

即当另一方删除时会级联删除第三方表中的数据,当然本表不会被删除。这点要注意 -->

<set name="students" table="tb_sc" inverse="true">

<key column="coid"/>

<many-to-many class="Student" column="stid"/>

</set>

</class>

 

<class name="Student_Course" table="tb_sc">

<composite-id name="scpk" class="Scpk">

<!-- 下面的设置很重要,foreign-key指定外键约束名称。不能相同,一但相同会将相同的覆盖

class指定外键所引用的主表,自动与主表的主键关联.

若是对应字段并没有参考其它表中的字段,也可以写成如下:

 <key-property column="stId"/>

 <key-property column="coId"/>

 -->

<key-many-to-one name="stId" column="stId" foreign-key="fkstid" class="Student"/>

<key-many-to-one name="coId" column="coId" foreign-key="fkcoid" class="Course"/>

</composite-id>

</class>

posted @ 2010-05-03 17:19  沉兮  阅读(476)  评论(0编辑  收藏  举报