Hibernate4继承映射

来源:互联网 发布:淘宝使用他人图片扣分 编辑:程序博客网 时间:2024/06/01 10:00

Hibernate 支持三种基本的继承映射策略:

1、单表继承:每棵类继承树使用一个表
2、具体表继承:每个子类一个表
3、类表继承:每个具体类一个表(有一些限制)


三种方式的比较:
1、所有类映射成一张表会产生数据冗余(不过这是通常采用的方法)
2、每个类映射成一张表会有效率问题,比如是三层或四层结构时,对于查询或更新会发出很多sql语句
3、具体类映射成表的缺点是主键不能自增

结论:使用第一种方式

 

Java代码  收藏代码
  1. /** 动物 */  
  2. public class Animal {  
  3.   
  4.     private Integer id;  
  5.     private String name;  
  6.     private String type;  
  7.   
  8.     //getter and setter  
  9. }  

 

Java代码  收藏代码
  1. /** 猪 */  
  2. public class Pig extends Animal {  
  3.   
  4.     private Double weight;  
  5.       
  6.     //getter and setter  
  7. }  

 

Java代码  收藏代码
  1. /** 鸟 */  
  2. public class Bird extends Animal{  
  3.   
  4.     private String color;  
  5.       
  6.     //getter and setter  
  7. }  

 

Xml代码  收藏代码
  1. <hibernate-mapping package="org.monday.hibernate4.domain">  
  2.     <class name="Animal" table="tbl_animal">  
  3.         <id name="id">  
  4.             <generator class="identity" />  
  5.         </id>  
  6.         <!-- 辨别者列 -->  
  7.         <discriminator column="type" type="string" />  
  8.         <property name="name" />  
  9.         <!-- 子类 -->  
  10.         <subclass name="Pig" discriminator-value="p">  
  11.             <property name="weight" />  
  12.         </subclass>  
  13.         <!-- 子类 -->  
  14.         <subclass name="Bird" discriminator-value="b">  
  15.             <property name="color" />  
  16.         </subclass>  
  17.     </class>  
  18. </hibernate-mapping>  

 下面是基于注解的

 

Java代码  收藏代码
  1. /** 动物 */  
  2. @Entity  
  3. @Table(name = "tbl_animal")  
  4. @Inheritance(strategy = InheritanceType.SINGLE_TABLE)  
  5. @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)  
  6. @DiscriminatorValue("a")  
  7. public class Animal {  
  8.   
  9.     @Id  
  10.     @GeneratedValue(strategy = GenerationType.IDENTITY)  
  11.     private Integer id;  
  12.   
  13.     private String name;  
  14.   
  15.     // getter and setter  
  16. }  

 

Java代码  收藏代码
  1. /** 猪 */  
  2. @Entity  
  3. @DiscriminatorValue("p")  
  4. public class Pig extends Animal {  
  5.   
  6.     private Double weight;  
  7.       
  8.     //getter and setter  
  9. }  

 

Java代码  收藏代码
  1. /** 鸟 */  
  2. @Entity  
  3. @DiscriminatorValue("b")  
  4. public class Bird extends Animal {  
  5.   
  6.     private String color;  
  7.   
  8.     // getter and setter  

0 0