1.在开发中,有的类信息比较复杂,而且某几个信息可以组成某一个部分,这个时候可以采用组件映射,组件映射是一张表映射到多个类。表结构
2.类的设计
Link.java
public class Link { private String phone; private String qq; private String email; private String address; public Link() { } public Link(String phone, String qq, String email, String address) { super(); this.phone = phone; this.qq = qq; this.email = email; this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
Person.java
public class Person { private int id; private String name; private int age; private Link link; public Person() { } public Person(String name, int age, Link link) { super(); this.name = name; this.age = age; this.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; } }
3.映射文件信息
<hibernate-mapping package="cn.sxt.pojo"> <class name="Person" table="t_person_info"> <id name="id"> <generator class="native"> </generator> </id> <property name="name"/> <property name="age"/> <!-- 组件映射 --> <component name="link" class="Link"> <property name="phone"/> <property name="qq"/> <property name="email"/> <property name="address"/> </component> </class> </hibernate-mapping>
4.测试
public class HibernateTest { /** * 生成数据库表的工具方法 * */ @Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport se = new SchemaExport(cfg); //第一个参数 是否打印sql脚本 //第二个参数 是否将脚本导出到数据库中执行 se.create(true, true); } /** * 初始化表数据 */ @Test public void testInit(){ Session session = null; Transaction tx = null; try { session = HibernateUtil.getSession(); tx = session.beginTransaction(); Link l1 = new Link("1324115534","345324","[email protected]","多伦多"); Link l2 = new Link("1345432367","675754","[email protected]","纽约"); Person p1 = new Person("mike",23,l1); Person p2 = new Person("lily",40,l2); session.save(p1); session.save(p2); tx.commit(); } catch (Exception e) { if(tx!=null) tx.rollback(); }finally { HibernateUtil.close(); } } /** */ @Test public void testGetData(){ Session session = HibernateUtil.getSession(); Person p1 = (Person)session.get(Person.class, 1); System.out.println(p1); HibernateUtil.close(); } }