继承映射在 Annotation 中使用 @Inheritance 注解,并且需要使用 strategy 属性指定继承策略,继承策略有 SINGLE_TABLE、TABLE_PER_CLASS 和 JOINED 三种。
- JOINED
A strategy in which fields that are specific to a subclass are mapped to a separate table than the fields that are common to the parent class, and a join is performed to instantiate the subclass.
示例:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {// 父类
@Id
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
子类:
@Entity
public class Patient extends Person{// 子类
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
执行效果:
Hibernate:
create table Patient (
name varchar(255),
id varchar(255) not null,
primary key (id)
)
Hibernate:
create table Person (
id varchar(255) not null,
primary key (id)
)
Hibernate:
alter table Patient
add constraint FKfrmgxot2hoa8g5w564a9adaye
foreign key (id)
references Person – 自动生成外键关联
- TABLE_PER_CLASS
A table per concrete entity class.
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person {
@Id
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
子类:
import javax.persistence.Entity;
@Entity
public class Patient extends Person{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
执行效果:
Hibernate:
create table Patient (
id varchar(255) not null,
name varchar(255),
primary key (id)
)
Hibernate:
create table Person (
id varchar(255) not null,
primary key (id)
)
- SINGLE_TABLE
A single table per class hierarchy.
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Person {
@Id
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
子类
import javax.persistence.Entity;
@Entity
public class Patient extends Person{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
执行效果:
Hibernate:
create table Person (
DTYPE varchar(31) not null,
id varchar(255) not null,
name varchar(255),
primary key (id)
)