Hibernate继承映射学习

1.课前准备

父类 Car

public class Car {
	private int id;
	private String name;
	
	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;
	}
	
}

子类Benz

public class Benz extends Car{
	private int id;
	private int price;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
}

子类Bwm

public class Bwm extends Car{
	private int id;
	private int speed;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getSpeed() {
		return speed;
	}
	public void setSpeed(int speed) {
		this.speed = speed;
	}
	
}

2.效果一:生成一张表

配置文件如下

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pk.po">
	<class name="Car" table="tb_car">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<discriminator column="type" type="string"></discriminator>
		<property name="name"></property>
		<subclass name="Bwm" discriminator-value="m">
			<property name="speed"></property>
		</subclass>
		<subclass name="Benz" discriminator-value="z">
			<property name="price"></property>
		</subclass>
	</class>
</hibernate-mapping>

效果二:每个类生成一张表

配置文件如下

<hibernate-mapping package="com.pk.po">
	<class name="Car" table="tb_Car">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name"></property>
		<subclass name="Benz" table="tb_benz">
			<key column="id"/>//参照Car的id
			<property name="price"></property>
		</subclass>
		<subclass name="Bwm" table="tb_bwm">
			<key column="id"/>//参照Car的id
<property name="speed"></property></subclass></class></hibernate-mapping>


效果三:每个子类生成一张表
<hibernate-mapping package="com.pk.po">
	<class name="Car" abstract="true">
		<id name="id">
			<generator class="assigned"></generator>
		</id>
		<property name="name"></property>
		<union-subclass name="Benz" table="tb_benz">
			<property name="price"></property>
		</union-subclass>
		<union-subclass name="Bwm" table="tb_bwm">
			<property name="speed"></property>
		</union-subclass>
	</class>
</hibernate-mapping>

需要注意:第三种无法自动使Id自增,所以必须手动配置。

笔者推荐第三种方式 既避免了第一种的空字段浪费,有避免的第二种的查询不便。

希望在评论中看到你的建议

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值