Hibernate的继承映射

                                       Hibernate的继承映射

        在一个类层次映射成一个表时,定义的discriminator只在hibernate与数据库之间使用。在持久化类中并不需要定义discriminator字段,即使定义了,而且数据库中该字段不为空,程序中访问该字段也将得到null值。也就是说,discriminator对应用程序是不可见的。从DTD里也可以看出,discriminator没有name元素,也就是说持久化类中不必为相应column定义一个属性。hibernate根据对象的具体类并参照映射文件中的discriminator字段来确定数据库中记录的更新、保存以及加载。采用这种策略只需要一张表即可。它有一个很大的限制:要求那些由子类定义的字段,不能有非空(NOT NULL)约束。

        在每个子类一张表时,连同超类,按照下面的实例,数据库中需要三张表。子类表通过主键关联到超类表(因而关系模型实际上是一对一关联)。子类中 的idPayment在数据库中可以设置成主键。

1、一个类层次对应一个表

< hibernate-mapping >
    
< class  name ="com.persistent.Payment"  table ="payment"   >     
        
< id  name ="id"  column ="paymentId"  unsaved-value ="null" >
            
< generator  class ="increment" ></ generator >
        
</ id >         
        
< discriminator  column ="paymentType" ></ discriminator >         
        
< property  name ="amount"  column ="amount" ></ property >         
        
< subclass  name ="com.persistent.CashPayment"  discriminator-value ="cash" >
            
< property  name ="cashType"  column ="cashType" ></ property >
        
</ subclass >         
        
< subclass  name ="com.persistent.CardPayment"  discriminator-value ="card" >
            
< property  name ="cardNumber"  column ="cardNumber" ></ property >
        
</ subclass >     
    
</ class >
</ hibernate-mapping >

2、每个子类一张表

< hibernate-mapping >
    
< class  name ="com.persistent.Payment"  table ="payment"   >     
        
< id  name ="id"  column ="paymentId"  unsaved-value ="null" >
            
< generator  class ="increment" ></ generator >
        
</ id >         
        
< property  name ="amount"  column ="amount" ></ property >         
        
< joined-subclass  name ="com.persistent.CashPayment"  table ="cashpayment" >
            
< key  column ="idPayment" ></ key >
            
< property  name ="cashType"  column ="cashType" ></ property >
        
</ joined-subclass >         
        
< joined-subclass  name ="com.persistent.CardPayment"  table ="cardpayment" >
            
< key  column ="idPayment" ></ key >
            
< property  name ="cardNumber"  column ="cardNumber" ></ property >
        
</ joined-subclass >     
    
</ class >
</ hibernate-mapping >

 

你可能感兴趣的:(数据库,Hibernate,table,Class,generator,payment)