能一张数据库表中包含了许多的字段:姓字段,名字段,电话字段,邮箱字段。其中可以看出来,姓字段和名字段可以细划分为姓名类别,电话和邮箱可以细划分为联系方式类别。而将此表映射到实体对象时,就可以分为2个实体类,姓名类和联系方式类。个人理解这样可以将表中没有划分的共通属性提炼出来。但有多张表中有联系方式和姓名类型字段时,可以用同一个实体类来映射,增加了复用性。
实现该映射方式的为:
1.建一个person类来映射数据库中的表
public class Person {
private int id ; private Name name ; Name类为姓名的实体类 private Contact contact ; Contact类为联系方式的实体类
public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Name getName() { return name; } public void setName(Name name) { this.name = name; }}
2.各建立Name类和Contact类
public class Name { private String firstname ; private String lastname ; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; }}
public class Contact { private String address ; private String zipcode ; private String tel ; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; }}
3.在hbm配置文件中用component节点
<?xml version="1.0" encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="org.lxh.hibernate">
<class name="Person" table="PERSON"> <id name="id" column="ID" type="int"> <generator class="assigned" /> </id> <component name="name" class="org.lxh.hibernate.Name"> <property name="firstname" column="FIRSTNAME" type="string" not-null="true" /> <property name="lastname" column="LASTNAME" type="string" not-null="true" /> </component> <component name="contact" class="org.lxh.hibernate.Contact"> <property name="address" column="ADDRESS" type="string" not-null="true" /> <property name="zipcode" column="ZIPCODE" type="string" not-null="true" /> <property name="tel" column="TEL" type="string" /> </component> </class>
</hibernate-mapping>