1. 在hibernate的关联映射中,有可能一张表映射为多张表,也有可能一个类映射为多张表。其中的组件映射就是一张表映射多张表。
2. 组件指一个类某一部分信息可以单独作为一个类存在,并且开发更方便,比如:人的联系方式:
3.类的结构: Link.java
public class Link { private String qq; private String phone; private String email; public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
Person.java
public class Person { private int id; private String name; private int age; private Link link; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Link getLink() { return link; } public void setLink(Link link) { this.link = link; } }
4. 映射文件 Person.hbm.xml
<hibernate-mapping> <class name="cn.sxt.vo.Person" table="t_person_info"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <property name="age"/> <component name="link" class="cn.wh.vo.Link"> <property name="qq"/> <property name="phone"/> <property name="email"/> </component> </class> </hibernate-mapping>
5. 测试:
public class HibernateTest { private Session session=null; @Before public void setUp(){ session = HibernateUtil.getSession(); } @After public void tearDown(){ HibernateUtil.close(); } @Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); //第一个参数 是否打印 数据库脚本 //第二个参数 是否将脚本导入数据库执行 export.create(true, true); } @Test public void testInit(){ Transaction tx = null; try { tx = session.beginTransaction(); Link l1 = new Link(); l1.setQq("23421341"); l1.setPhone("132345322"); l1.setEmail("z@qq.com"); Person p1 = new Person(); p1.setName("张三"); p1.setAge(23); p1.setLink(l1); session.save(p1); tx.commit(); } catch (Exception e) { if(tx!=null) tx.rollback(); } } @Test public void testGet(){ Person p = (Person)session.get(Person.class, 1); System.out.println(p.getName()+"---"+p.getAge()+"---"+p.getLink().getEmail()); } }