组件(Component)映射多用来表示对象的从属关系(组合,聚合).比如一个学生可能有姓名,年龄,性别,成绩等属性,其中成绩是另一个对象,又有科目,分数属性,这里就需要用组件映射来表是之间的关系.
Java代码:
// 学生
class Student{
private String name;
private int age;
private String sex;
private Grade grade;
}
// 成绩
class Grade{
private String subject;
private float score;
}
数据库:
-- 学生表
create table STUDENT (
ID char(32) not null,
NAME varchar(16) not null,
SEX char(1),
AGE integer,
primary key (ID)
);
-- 成绩表
create table GRADE (
ID char(32) not null,
student_id char(32) not null,
SUBJECT varchar(10),
SCORE float,
primary key (ID),
foreign key (student_id)
); Hibernate映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="Student" table="STUDENT">
<id name="id" type="string" unsaved-value="null">
<column name="ID" sql-type="char(32)"/>
<generator class="uuid.hex"/>
</id>
<property name="name" type="string" not-null="true">
<column name="NAME" length="16" not-null="true"/>
</property>
<property name="sex" type="char" column="SEX"/>
<property name="age" type="int" column="AGE"/>
<component name="grade" class="Grade">
<property name="subject" type="string" column="SUBJECT" not-null="true"/>
<property name="score" type="float" column="SCORE" not-null="true"/>
</component>
</class>
</hibernate-mapping>
posted on 2005-12-22 18:46
ZhuJun 阅读(773)
评论(0) 编辑 收藏 所属分类:
开发手记 、
开源项目