【SSH快速进阶】——Hibernate继承映射:每个类映射一张表
2016-02-20 10:49
387 查看
上文说了每棵继承树映射一张表,本文继续描述让每个类都映射一张表的配置。
场景
与上篇文章场景一样,如下类图
上图中Pig类和Bird类继承Animal类,要让每个类映射一张表,就是让着三个类都分别映射一张表,但同时这三张表也跟对应的三个类似的,有继承关系,如下表所示:
(表 1)
Pig和Bird的记录都表示一个动物,因此都会在Animal对应的表中存储,而它们各自的拓展属性则存储在各自对应的表中,主键与Animal对应记录的主键各自对应。
配置
PO对象
跟上篇文章一样,实体类没有任何变化。
Animal.java
[code]public class Animal { private int id; private String name; private boolean sex; //getter、setter }
Bird.java
[code]public class Bird extends Animal{ private int height; //getter、setter }
Pig.java
[code]public class Pig extends Animal{ private int weight; //getter、setter }
映射文件
配置映射文件时,父类还用
<class>标签来定义即可;用
<joined-subclass>标签定义两个子类,与父类“合并”在同一张表里,同时,子类对应表中记录的主键与父类表中记录的主键一一对应;子类的特有属性同样用
<property>定义即可。
Extends.hbm.xml
[code]<hibernate-mapping package="com.danny.hibernate"> <class name="Animal"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="sex"/> <joined-subclass name="Pig" table="t_pig"> <key column="pid" /> <property name="weight"/> </joined-subclass> <joined-subclass name="Bird" table="t_bird"> <key column="bid"/> <property name="height"/> </joined-subclass> </class> </hibernate-mapping>
启动程序执行的建表语句如下,一共建立了三张表,并且两个子类对应表中的主键与父类对应表中的主键一致:
[code]alter table t_bird drop foreign key FKCB5B05A431E44651 alter table t_pig drop foreign key FK68F874331E47ADF drop table if exists t_animal drop table if exists t_bird drop table if exists t_pig create table t_animal (id integer not null auto_increment, name varchar(255), sex bit, primary key (id)) create table t_bird (bid integer not null, height integer, primary key (bid)) create table t_pig (pid integer not null, weight integer, primary key (pid)) alter table t_bird add index FKCB5B05A431E44651 (bid), add constraint FKCB5B05A431E44651 foreign key (bid) references t_animal (id) alter table t_pig add index FK68F874331E47ADF (pid), add constraint FK68F874331E47ADF foreign key (pid) references t_animal (id)
测试
这种方案相对于上层实现(增删改查等操作)不变,因为对象模型并没有改变,只是关系模型改了,只需要修改映射文件即可。
所以对对象的操作同上篇文章《【SSH快速进阶】——Hibernate继承映射:每棵继承树映射一张表》中的测试一致。
总结
缺点:查询时需要关联表,效率差;插入时也要执行多个insert语句,适合继承程度不深的情况。
优点:粒度较细,调理清楚,没有冗余。
在表1中就可以看出,父类是真正意义上的“父类”,因此,如果父类是抽象类或者没有实际意义的话,可以用此方案。
【 转载请注明出处——胡玉洋《【SSH快速进阶】——Hibernate继承映射:每个类映射一张表》】
相关文章推荐
- 4个理由告诉你Java为何排行第一
- 由浅入深漫谈margin属性
- bzoj 3238: [Ahoi2013]差异 后缀数组
- mysql设计的注意地方
- 第四天
- 《大话设计模式》读书笔记3 面向对象设计五个基本原则
- 关于utf-8(网上查阅)
- ANDROID_MARS学习笔记_S03_001_获取蓝牙匹配列表
- Android listview只显示一行的解决方法(计算listview的高度)
- MySQL具体解释(19)----------海量数据分页查询优化
- caffe配置问题与解决方法集锦
- 【JAVA】 基础练习 BASIC-6 杨辉三角形
- SVN数据仓库迁移
- 爬楼梯问题
- 有若干个字符串,比較找出当中最大者
- MySql_安装及简单命令
- Struts2--Global Result全局结果集
- C++11新标准
- 学习pthreads,给线程传递多个參数
- 怎么修改gif图片中的文字[实用]