【Hibernate】继承映射

         继承映射是将一个继承体系映射到数据库表里面,继承实现的三种策略:

①单表继承,每颗类继承树使用一张表(一张表)

②具体表继承,每个子类一张表(三张表,animalpigbird

③类表继承,每个具体类一张表(两张表,pigbird


策略描述

①单表继承,效率较高,只需查一张表就好,需要添加一个标记字段来标记是哪个子类,而且会产生冗余的字段。

②具体表继承,生成的表比较清楚,当数量非常大的时候效率不高,类的继承层次越深,关联的表越多。

③类表继承,每个类在映射文件中都需要描述,抽象的类没有具体的表,不能使用自增字段作为主键

实体类

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>

效果展示

①单表继承


②具体表继承



③类表继承


小结

         每种继承映射都有自己的利弊,根据继承类层次的深度和类的多少,以及数据的多少合理选择使用哪种继承策略。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值