您的位置:首页 > 其它

【Hibernate】继承映射

2017-01-17 11:49 253 查看
         继承映射是将一个继承体系映射到数据库表里面,继承实现的三种策略:
①单表继承,每颗类继承树使用一张表(一张表)
②具体表继承,每个子类一张表(三张表,animal、pig、bird)
③类表继承,每个具体类一张表(两张表,pig、bird)



策略描述
①单表继承,效率较高,只需查一张表就好,需要添加一个标记字段来标记是哪个子类,而且会产生冗余的字段。
②具体表继承,生成的表比较清楚,当数量非常大的时候效率不高,类的继承层次越深,关联的表越多。
③类表继承,每个类在映射文件中都需要描述,抽象的类没有具体的表,不能使用自增字段作为主键
实体类
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;
}
}

public class Pig extends Animal{

private int weight;

public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight=weight;
}
}

public class Bird extends Animal{

private int height;

public int getHeight(){
return height;
}
public void setHeight(int height){
this.height=height;
}
}
映射
①单表继承
<hibernate-mapping package="com.tgb.hibernate">
<class name="Animal" table="t_animal">
<id name="id">
<generator class="native"/>
</id>

<!--加入鉴别字段-->
<discriminator column="type" type="string"/>
<property name="name"/>
<property name="sex"/>

<!--加入鉴别值 discriminator-value-->
<subclass name="Pig" discriminator-value="P">
<property name="weight"/>
</subclass>
<subclass name="Bird" discriminator-value="B">
<property name="height"/>
</subclass>
</class>
</hibernate-mapping>
②具体表继承
<hibernate-mapping package="com.tgb.hibernate">
<class name="Animal" table="t_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>
③类表继承
<hibernate-mapping package="com.tgb.hibernate">
<class name="Animal">
<id name="id">
<generator class="assigned"/>
</id>
<property name="name"/>
<property name="sex"/>
<union-subclass name="Pig" table="t_pig">
<property name="weight"/>
</union-subclass>
<union-subclass name="Bird" table="t_bird">
<property name="height"/>
</union-subclass>
</class>
</hibernate-mapping>
效果展示
①单表继承



②具体表继承





③类表继承



小结
        
每种继承映射都有自己的利弊,根据继承类层次的深度和类的多少,以及数据的多少合理选择使用哪种继承策略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: