用到的POJO代码如下:
public class Member {
private String id;
private String name;
private Integer age;
private Address homeAddress;
private Address billingAddress;
......
}
public class Address {
private String street;
private String zipCode;
private String city;
......
}
对于Member来说,Address是它的一个组件。下面是对应的映射文件。
<hibernate-mapping package="org.louis.domain">
<class name="Member" table="TEST_MEMBER">
<id name="id" column="ID">
<generator class="uuid.hex"></generator>
</id>
<property name="age" column="AGE"></property>
<property name="name" column="NAME"></property>
<component name="homeAddress" class="Address">
<property name="street" column="home_street"></property>
<property name="zipCode" column="home_zip_code"></property>
<property name="city" column="home_city"></property>
</component>
<component name="billingAddress" class="Address">
<property name="street" column="billing_street"></property>
<property name="zipCode" column="billing_zip_code"></property>
<property name="city" column="billing_city"></property>
</component>
</class>
</hibernate-mapping>
在上面的Member.hbm.xml文件中,Address作为Member的组件被定义,共使用了两次,分别对应于Member的两个属性。根据配置文件知道,Member可以获得它的组件,儿Address却不能得到它的所有者,如果也想让Address得到它的所有者,可以在<component>中添加一个节点<parent name="Member",同时在Address的类中增加member属性,并提供getter和setter方法即可使用如address.getMember()来操作Member类。
运行测试代码:
public void insert() {
Session session = HibernateSessionFactory.getSessionFactory()
.getCurrentSession();
session.beginTransaction();
Member m = new Member();
m.setAge(24);
m.setName("Louis");
Address homeAddress = new Address();
homeAddress.setCity("南阳");
homeAddress.setStreet("nanyang");
homeAddress.setZipCode("nanyang");
Address billingAddress = new Address();
billingAddress.setCity("上海");
billingAddress.setStreet("shanghai");
billingAddress.setZipCode("shanghai");
m.setHomeAddress(homeAddress);
m.setBillingAddress(billingAddress);
session.save(m);
session.getTransaction().commit();
}
后台SQL语句如:
Hibernate:
insert
into
TEST_MEMBER
(AGE, NAME, home_street, home_zip_code, home_city, billing_street, billing_zip_code, billing_city, ID)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?)
由此可见,Hibernate会把TEST_MEMBER表的字段进行解析,把对应的值设置到homeAddress和billingAddress对象中。