hibernate 组件(Component)映射

1、类Teacher

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

2、类Teacher的组件 Address

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

3、Teacher.hbm.xml

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

4、 测试

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

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/jiangjianzhu/p/5546388.html