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; } }
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; } }
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; } }
配置文件如下
<?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自增,所以必须手动配置。笔者推荐第三种方式 既避免了第一种的空字段浪费,有避免的第二种的查询不便。
希望在评论中看到你的建议
复制 搜索复制 搜索复制 搜索复制 搜索