前面几篇博客介绍了Hibernate的级联,映射关系等,该篇介绍hibernate类继承树映射为一张表,还是举例说明
首先创建一个实体继承树,实体的继承关系如图所示:
Pig对象和Bird对象都继承Animal,确定继承关系之后,可以将3个类映射到一张表tb_animal中,可通过字段type用来区分不同的实体对象信息
Animal对象类:
package com.hiberbate.manytomany;
public class Animal {
private int id;
private String name;
private boolean sex;
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 boolean getSex(){
return sex;
}
public void setSex(boolean sex){
this.sex = sex;
}
}
Pig对象类:
package com.hiberbate.manytomany;
public class Pig extends Animal{
private int weight;
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight = weight;
}
}
Bird对象类:
package com.hiberbate.manytomany;
public class Bird extends Animal{
private int height;
public int getHeight(){
return height;
}
public void setHeight(int height){
this.height = height;
}
}
映射文件tb_annimal.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.hiberbate.manytomany">
<class name="Animal" table="tb_animal">
<id name="id" column="id" type="int" >
<!-- 主键生成策略 -->
<generator class="assigned" />
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="sex" type="boolean" column="sex"></property>
<subclass name="Bird" discriminator-value="B">
<property name="height"></property>
</subclass>
<subclass name="Pig" discriminator-value="P">
<property name="weight"></property>
</subclass>
</class>
</hibernate-mapping>
创建tb_animal表如图所示:
下面做测试:
private static void classextentsTree() {
Session session = null;
Pig pig=new Pig();
pig.setId(5);
pig.setName("小猪");
pig.setSex(true);
pig.setWeight(200);
Bird bird=new Bird();
bird.setId(3);
bird.setName("小鸟");
bird.setSex(false);
bird.setHeight(100);
Animal animal=new Animal();
animal.setId(100);
animal.setName("小动物");
animal.setSex(false);
try {
session = HibernateUtil.getSession();
//添加数据
session.beginTransaction();
session.save(pig);
session.save(bird);
session.save(animal);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
System.out.print("数据库添加失败");
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
结果如图: