1. 首页
  2. 软件开发
  3. SpringData——JPA实体的继承策略(Single Table, Joined, Table Per Class)

SpringData——JPA实体的继承策略(Single Table, Joined, Table Per Class)

  • 发布于 2024-08-17
  • 1 次阅读

在JPA中,实体的继承策略定义了如何将继承关系映射到数据库中的表结构。常见的继承策略包括Single Table(单表继承)、Joined(连接表继承)和Table Per Class(每个类对应一个表)。

1. Single Table(单表继承)

所有子类共享一个数据库表,使用一个类型字段来区分不同的子类。

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type", discriminatorType = DiscriminatorType.STRING)
public class Employee {
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
   
}

@Entity
@DiscriminatorValue("manager")
public class Manager extends Employee {
   
    private String department;
}

@Entity
@DiscriminatorValue("developer")
public class Developer extends Employee {
   
    private String programmingLanguage;
}

2. Joined(连接表继承)

每个类对应一个数据库表,子类表通过外键与父类表关联。

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee {
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
   
}

@Entity
public class Manager extends Employee {
   
    private String department;
    
}

@Entity
public class Developer extends Employee {
   
    private String programmingLanguage;
    
}

3. Table Per Class(每个类对应一个表)

每个类都有自己的数据库表,包含父类和子类的所有属性。

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Employee {
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

@Entity
public class Manager extends Employee {
   
    private String department;
}

@Entity
public class Developer extends Employee {
   
    private String programmingLanguage;
}

原文链接: https://blog.csdn.net/2401_82884096/article/details/137016244