1、类Teacher

1
2
3
4
5
6
7
public class Teacher {
private int id;
private String name;
private String sex;
private Address address;
//省略get/set
}

2、类Teacher的组件 Address

1
2
3
4
5
6
public class Address {
private String addr1;
private String addr2;
private String addr3;
//省略get/set
}

3、Teacher.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<hibernate-mapping package="cn.siggy.pojo">
<class name="Teacher">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"/>
<property name="sex"/>
<!-- 组件 -->
<component name="address" class="Address">
<property name="addr1"/>
<property name="addr2"/>
<property name="addr3"/>
</component>
</class>
</hibernate-mapping>

4、测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Test
public void testSave() throws HibernateException, SerialException, SQLException{
Session session = null;
Transaction tx = null;
try{
session = HibernateUtil.getSession();
tx = session.beginTransaction();
Teacher t = new Teacher();
t.setName("老裴");
t.setSex("男");
Address address = new Address();
address.setAddr1("西三旗");
address.setAddr2("西直门");
address.setAddr3("南六环");
t.setAddress(address);

session.save(t);
tx.commit();
}catch (HibernateException e) {
if(tx!=null)
tx.rollback();
e.printStackTrace();
throw e;
}finally{
HibernateUtil.closeSession();
}
}