JPA中的InheritanceType用于定义实体的继承映射策略,有以下类型:
- SINGLE_TABLE:单表继承映射。父类和子类共享同一张表,使用discriminator列区分类型。
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE")
public class Person { ... }
@Entity
public class Employee extends Person { ... }
- TABLE_PER_CLASS:各类一表继承映射。每一个实体类对应一张表,不共享表。
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person { ... }
@Entity
public class Employee extends Person { ... }
- JOINED:联接继承映射。父类和子类各自的表,并且有外键相连。
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person { ... }
@Entity
public class Employee extends Person { ... }
- MappedSuperclass:将父类映射为抽象类,其不映射为表,仅用于提供字段映射信息。
@MappedSuperclass
public abstract class Person { ... }
@Entity
public class Employee extends Person { ... }
代码示例:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE")
public class Person {
@Id
private int id;
}
@Entity
public class Employee extends Person {
private double salary;
}