hibernate继承映射

每一个实体类都有一些对象,对象是数据的载体,每个对象在数据库中可能是一条或多条数据。而实体类之间存在继承关系,所以在数据库中表格之间也存在相应的继承关系。强大的对象关系管理(ORM)hibernate,也提供了三种方式的解决方案。

  1. 一个类对应一张表
  2. 一个子类对应一张分表
  3. 一个继承体系对应一张表

我们将根据下面这个类的关系做具体讲解:

hibernate继承映射_第1张图片
  • 一个子类对应一张表
    每一个子类对应的数据库表都包含了父类的信息,并且包含了自己独有的属性。每个子类对应一张表,而且这个表的信息是完备的,即包含了所有从父类继承下来的属性映射的字段。
  1. Person.hbm.xml

    
        
            
        
        
        
        
            
        
        
            
        
    

  1. teacher.sql
 create table t_teacher (
  id integer not null,
  name varchar(20),
  salary float, 
  primary key (id)
) engine=InnoDB
  1. student.sql
create table t_student (
  id integer not null,
  name varchar(20),
  major varchar(20), 
  primary key (id)
) engine=InnoDB
  1. person.sql
create table t_Person (
  id integer not null,
  name varchar(20),
  primary key (id)
) engine=InnoDB
  • 一个子类对应一张分表

每一个子类对应的数据库表只包含了自己独有的属性。每个子类对应一张表,而且这个表的信息是不完备的。

  1. person.hbm.xml

    
        
            
        
        
        
        
            
            
        
        
        
            
            
        
    

  1. person.sql
create table t_Person (
 id integer not null,
 name varchar(20),
 primary key (id)
) engine=InnoDB


  1. student.sql
create table t_student (
 id integer not null, 
 major varchar(20), 
 primary key (id)
) engine=InnoDB
  1. teacher.sql
create table t_teacher (
 id integer not null, 
 salary float, 
 primary key (id)
) engine=InnoDB
  1. 最后添加外键
alter table t_student add constraint FK1dntcikk4ddyfgyfif10kwp9c foreign key (id) references t_Person (id)
alter table t_teacher add constraint FKc2hk0m55tq5nmse34dhgyd5gc foreign key (id) references t_Person (id)
  • 一个继承体系对应一张表
    这种关系通过标签来实现,区分类和角色,增加一个字段
  1. person.hbm.xml

    
        
            
        

        
    
        
        
        
            
        
        
            
        
    

  1. person.sql
create table t_Person (
 id integer not null, 
 type varchar(255) not null, 
 name varchar(20), 
 major varchar(20), 
 salary float, 
 primary key (id)
) engine=InnoDB

你可能感兴趣的:(hibernate继承映射)