您的位置:首页 > 其它

hibernate笔记--组件映射方法

2016-03-02 19:30 387 查看
  假设我们需要保存学生student的信息,student中有一个address属性,我们知道像这种信息其值可能会有多个,就像一个人会有两个以上的手机号,这种情况在hibernate中应该这样配置:

新建一个Address类,我们假设每个学生最多能保存3个地址:

public class Address {

private String addr1;
private String addr2;
private String addr3;

//get/set方法省略
}


新建student实体类:

public class Student {

private int id;
private String name;
private String sex;
private Address address;
//get/set方法省略
}


在当前包下新建一个Student.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.wang.pojo">
<class name="Student" >
<id    name="id">
<generator class="native"></generator>
</id>

<property name="name"></property>
<property name="sex"></property>
<component name="address" class="Address" >
<property name="addr1"></property>
<property name="addr2"></property>
<property name="addr3"></property>
</component>
</class>
</hibernate-mapping>


新建一个测试类,来自动生成数据库的表,以及向数据库表中添加一条数据:

@Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure();
SchemaExport se = new SchemaExport(cfg);
// 第一个参数是否生成ddl脚本 第二个参数是否执行到数据库
se.create(true, true);
}

@Test
public void testSave() {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
Student s = new Student("张三", "男", new Address("山东省", "湖北省", "浙江省"));
session.persist(s);
tx.commit();
session.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: