hibernate关联映射之组件映射(component)实例。hibernate里面component为某个实体的逻辑组成部分,其与实体的根本区别就是没有oid,component可以是值对象(DDD)。采用component映射的优势是它实现了对象模型的细粒度划分,层次会更分明,复用率会更高。
例如:User对象有一系列联系方式,如电话号码,email,地址等,Admin对象也有一系列与User对象的联系方式。如果我们将联系方式抽取成一个类,那我们如何用hibernate设计呢?答案:使用组件映射,即:component。
代码实现:
1) 建立联系方式类,即Contact.java
public class Contact { private String email; private String address; private String zipCode; private String contactTel; |
2) 建立User类和Admin对象(Admin忽略),在对象中加入Contact类的属性
public class User { private int id; private String name; private Contact contact; |
3) 建立映射文件,User.hbm.xml和Admin.hbm.xml(忽略)
<hibernate-mapping> <class name=”User” table=”t_user”> <id name=”id”> <generator class=”native”/> </id> <property name=”name”/> <component name=”contact”> <property name=”email”/> <property name=”address”/> <property name=”zipCode”/> <property name=”contactTel”/> </component> </class> </hibernate-mapping> |
4) 建立测试代码:
public class ComponentMappingTest extends TestCase { public void testSave1() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction();
User user = new User(); user.setName(“张三”);
Contact contact = new Contact(); contact.setAddress(“xxxxx”); contact.setEmail(“xxx@rrr.com”); contact.setZipCode(“1111111″); contact.setContactTel(“9999999999″);
user.setContact(contact);
session.save(user); session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } } } |