建立一个相关的数据库表:
[sql]
create table c_user(
id int(11) not null auto_increment,
age int(11) default null,
firstname varchar(50) default null,
lastname varchar(50) default null,
address varchar(200) default null,
zipcode varchar(10) default null,
tel varchar(20) default null,
primary key(id)
)engine=innodb default charset=gbk;
注解:该表是一个用户信息表,可以将用户信息归纳为两个部分:一个部分是name(姓名),包含firstname(姓)和lastname(名);另一部分是contact(联系方式),包括了address(地址)、zipcode(邮编)和tel(电话)等信息。在创建实体类时,可以将name和contact分别封装到2个独立的类中,这样就提高了系统的复用性和灵活性。也就是说,需要使用Component映射,将其他的实体类映射在一起。
建立一个Name.java类:
[java]
package collect.component;
import java.io.Serializable;
public class Name implements Serializable {
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;
}
}
建立联系方式相关的类Contact.java:
[java]
package collect.component;
import java.io.Serializable;
public class Contact implements Serializable{
private String address;
private String zipcodes;
private String tel;
public Contact() {}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipcodes() {
return zipcodes;
}
public void setZipcodes(String zipcodes) {
this.zipcodes = zipcodes;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
最后建立数据库表对应的实体类Cuser.java:
[java]
package collect.component;
public class Cuser {
private Integer id;
private Integer age;
private Name name;
private Contact contact;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
建立映射文件Cuser.hbm.xml:
[html]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="collect.component.Cuser" table="c_user" catalog="ssh">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="age" type="integer">
<column name="age" />
</property>
<component name="name" class="collect.component.Name">
<property name="firstname" type="string">
<column name="firstname" length="50" />
</property>
<property name="lastname" type="string">
<column name="lastname" length="50" />
</property>
</component>
<component name="contact" class=&q
补充:软件开发 , Java ,