两种针对继承的HBM文件编写方法

首先,有三个实体对象User,Student, Teacher

其中三者共同的属性是name,password,fullname,均定义在User中,Student和Teacher继承User

如果要在hibernate配置文件中定义上面的关系,有两种方法

(1)使用<union-subclass>
          使用这种方式,三个表的字段名称必须完全相同(name,password,fullname)

< class  table ="userinfo"  name ="cm.hxex.exam.model.User" >
    
< id  name ="id"  column ="ID" >
      
< generator  class ="uuid.hex" />
    
</ id >
    
< property  name ="name"  column ="NAME" />
    
< property  name ="password"  column ="PASSWORD" />
    
< property  name ="fullname"  column ="FULLNAME" />
    
< union-subclass  table ="teacher"  name ="cn.hxex.exam.mode.Teacher" >
        
< many-to-one  column ="class_id"  cascade ="save-update"  name ="classes" />
    
</ union-subclass >

     
< union-subclass  table ="student"  name ="cn.hxex.exam.mode.Student" >
       
< set  cascade ="all"  lazy ="true"  table ="TEACHER_CLASS"  name ="classes" >
         
< key  column ="TEACHER_ID" />
         
< many-to-many  class ="cn.hxex.exam.model.Classes"  column ="CLASS_ID" />
       
</ set >
     
</ union-subclass >
</ class >

 (2)使用单独的<class>

           可以解决字段名不一样的问题,但在每个子类中都要进行相应的属性定义,造成配置重复

  < class  table ="USERINFO"  name ="cn.hxex.exam.model.User" >
    
< id  name ="id"  column ="ID" >
      
< generator  class ="uuid.hex" />
    
</ id >
    
< property  name ="name"  column ="NAME" />
    
< property  name ="password"  column ="PASSWORD" />
    
< property  name ="fullname"  column ="FULLNAME" />
  
</ class >

    
< class  table ="STUDENT"  name ="cn.hxex.exam.model.Student" >
    
< id  name ="id"  column ="ID" >
      
< generator  class ="uuid.hex" />
    
</ id >
    
< many-to-one  column ="CLASS_ID"  cascade ="save-update"  name ="classes" />
    
< property  name ="name"  column ="NAME" />
    
< property  name ="password"  column ="PASSWORD" />
    
< property  name ="fullname"  column ="FULLNAME" />
  
</ class >

    
< class  table ="TEACHER"  name ="cn.hxex.exam.model.Teacher" >
    
< id  name ="id"  column ="ID" >
      
< generator  class ="uuid.hex" />
    
</ id >
    
< set  inverse ="true"  name ="papers" >
      
< key  column ="TEACHER_ID" />
      
< one-to-many  class ="cn.hxex.exam.model.TestPaper" />
    
</ set >
    
< set  cascade ="all"  lazy ="true"  table ="TEACHER_CLASS"  name ="classes" >
      
< key  column ="TEACHER_ID" />
      
< many-to-many  class ="cn.hxex.exam.model.Classes"  column ="CLASS_ID" />
    
</ set >
    
< property  name ="name"  column ="NAME" />
    
< property  name ="password"  column ="PASSWORD" />
    
< property  name ="fullname"  column ="FULLNAME" />
  
</ class >


你可能感兴趣的:(Hibernate)