您的位置:首页 > 其它

继承结构中每个子类单独一张表

2017-07-19 16:54 176 查看
在上一节《hibernate单表继承映射》中,我们讲了在继承结构中,我们把子类和父类放在同一张表中的写法,那种写法在实际开发中,也很多的不便,所以这节我们使用每个子类单独一张表的写法。

类的继承关系和上一节一样,如图:



新建一个java项目,项目结构如图:



jar和hibernate官网获取方法,请参见《Hibernate环境搭建和配置

Person、Teacher、Student以及HibernateUtil和hibernate.cfg.xml代码,都参考上一节《hibernate单表继承映射

不同的地方是Person.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.robert.pojo">
<!-- abstract="true":指明Person类是抽象的,不生成对应的person数据库表 -->
<class name="Person" abstract="true">
<id name="id" column="id">
<!-- assigned:自己指定主键 -->
<generator class="assigned"></generator>
</id>
<property name="name" />
<property name="age" />
<union-subclass name="Student" >
<property name="work"></property>
</union-subclass>
<union-subclass name="Teacher" >
<property name="salary"></property>
</union-subclass>
</class>
</hibernate-mapping>

当然同样是先生成数据库表,代码:

/**
* 根据*.hbm.xml文件对应的生成数据库表
*/
@Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure();
SchemaExport se = new SchemaExport(cfg);
// 第一个参数:是否生成ddl脚本
// 第二个参数:是否执行到数据库中
se.create(true, true);
}


运行后看到console的sql语句
drop table if exists Student

drop table if exists Teacher

create table Student (
id integer not null,
name varchar(255),
age integer,
work varchar(255),
primary key (id)
)

create table Teacher (
id integer not null,
name varchar(255),
age integer,
salary integer,
primary key (id)
)

数据库中生成的表如图:



只生成了两张表,没有生成person表,这是因为我们在Person.hbm.xml中指定了 abstract="true",



测试代码:
@Test
public void testSave() throws HibernateException, SerialException,
SQLException, IOException {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSession();
tx = session.beginTransaction();

Teacher t1 = new Teacher() ;
t1.setId(1) ;
t1.setAge(32) ;
t1.setName("张老师") ;
t1.setSalary(5000) ;

Student stu1 = new Student() ;
stu1.setId(2) ;
stu1.setAge(22) ;
stu1.setName("王同学") ;
stu1.setWork("家庭作业1") ;

Student stu2 = new Student() ;
stu2.setId(3) ;
stu2.setAge(24) ;
stu2.setName("刘同学") ;
stu2.setWork("housework") ;

session.save(t1) ;
session.save(stu1) ;
session.save(stu2) ;

tx.commit();

} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
throw e;
} finally {
HibernateUtil.closeSession();
}
}


运行保存代码,看到sql语句如:
Hibernate:
insert
into
Teacher
(name, age, salary, id)
values
(?, ?, ?, ?)
Hibernate:
insert
into
Student
(name, age, work, id)
values
(?, ?, ?, ?)
Hibernate:
insert
into
Student
(name, age, work, id)
values
(?, ?, ?, ?)


看到数据库表中的数据如图:



总结:

1、在每个具体类一张表的继承映射中,主键的生成不能使用identity,建议使用uuid,sequence,assigned等。

2、数据表的结构更加合理。多态查询效率不高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐