hibernate笔记--组件映射方法
2016-03-02 19:30
387 查看
假设我们需要保存学生student的信息,student中有一个address属性,我们知道像这种信息其值可能会有多个,就像一个人会有两个以上的手机号,这种情况在hibernate中应该这样配置:
新建一个Address类,我们假设每个学生最多能保存3个地址:
新建student实体类:
在当前包下新建一个Student.hbm.xml:
新建一个测试类,来自动生成数据库的表,以及向数据库表中添加一条数据:
新建一个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(); }
相关文章推荐
- 数据库安装检查
- 求绝对众数
- 丢点小东西
- FZU - 1707 (卡logN的题)
- Web Deploy发布网站一条龙解决方案
- Oracle 10g 11g 单机环境的安装
- python的命令模式和编辑模式
- ClockRepairs
- workman windows架构图
- 关于环境变量失效的问题
- 软件测试(一)之 error
- NYOJ-128-前缀式计算
- iOS(学习) UITabBarController
- RHEL 5 ORACLE Linux 5.9 配置YUM源 5配置yum
- Android 横竖屏切换
- IOS——线程的应用
- sql语句中的空值(null)
- 通过联网问题的解决看singress.exe应用程序
- Codeforces Round #343 (Div. 2) D. Babaei and Birthday Cake
- m1上 配置OEM 怎样配置oracle oem