首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

hibernate学习十之component(组件)映射

2012-10-28 
hibernate学习10之component(组件)映射在hibernate中,component是某个实体的逻辑组成部分,它与实体的根本

hibernate学习10之component(组件)映射
在hibernate中,component是某个实体的逻辑组成部分,它与实体的根本区别是没有oid,
component可以成为是值对象(DDD)

采用component映射的好处:它实现了对象模型的细粒度划分,层次会更分明,复用率会更高

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_component_mapping</property><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">bjsxt</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="hibernate.show_sql">true</property><mapping resource="com/bjsxt/hibernate/User.hbm.xml"/></session-factory></hibernate-configuration>

public class User {private int id;private String name;private Contact contact; //setter,getter}public class Contact {private String email;private String address;private String zipCode;private String contactTel;//setter,getter}

利用下面的配置就可以实现组件映射,它可以增加代码复用率,假定现在还有一个类也有email,address,zipCode,contactTel这些属性,那就可以使用Contact 类来减少setter&getter,实现代码复用。
User.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.bjsxt.hibernate.User" table="t_user"><id name="id"><generator name="code">import org.hibernate.Session;import junit.framework.TestCase;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);}}}

热点排行