组件属性:实体类中的某个属性属于用户自定义的类的对象。
eg:
上例,属性address就是一个组件属性(它是属于Address类的一个对象)。Address类又有3个字段:postcode、phone、address。
编写一个Address类,含有属性:
private String postcode;//邮编
private String phone;//电话
private String address;//地址
Students类中增加address属性及其get/set方法:
private int sid; //学号
private String sname; //姓名
private String gender; //性别
private Date birthday; //出生年月
// private String address; //地址
private Blob picture; //照片
private Address address;//地址
Students.hbm.xml中增加:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="Students" table="students" catalog="hibernate">
<id name="sid" type="java.lang.Integer">
<column name="sid" />
<!-- <generator class="assigned" />-->
<generator class="native" />
</id>
<property name="sname" type="java.lang.String">
<column name="sname" length="225" />
</property>
<property name="gender" type="java.lang.String">
<column name="gender" />
</property>
<property name="birthday" type="timestamp">
<column name="birthday" length="10" />
</property>
<!--
<property name="address" type="java.lang.String">
<column name="address" />
</property>
-->
<property name="picture" type="java.sql.Blob">
<column name="picture"></column>
</property>
<component name="address" class="Address">
<property name="postcode" column="postcode"></property>
<property name="phone" column="phone"></property>
<property name="address" column="address"></property>
</component>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<property name="hbm2ddl.auto">create</property>
使用Junit测试方法testSaveStudents:
@Test
public void testSaveStudents(){
//生成学生对象
// Students s=new Students(1,"张三丰","男",new Date(),"武当山");
Students s=new Students();
// s.setSid(1); //native:主键自动增长,无须赋值;若强制赋值无效果
s.setSname("张三丰");
s.setGender("男");
s.setBirthday(new Date());
// s.setAddress("武当山");
Address address=new Address("710068","02988567123","西安市");
s.setAddress(address);
//保存对象进入数据库
session.save(s);
}
运行成功,数据库添加数据成功: