描述

在数据库中存储类层次结构的另一种策略称为 Joined Table。它有一个特殊的注释:

@Inheritance(strategy = InheritanceType.JOINED)

我们班级的一个例子:

@Inheritance(strategy = InheritanceType.JOINED)
@Entity
class User {
  int id;
  String name;
  LocalDate birthday;
}
@Entity
class Employee extends User {
 	String occupation;
 	int salary;
 	LocalDate join;
}
@Entity
class Client extends User {
   String address;
}

当使用这个注解时,Hibernate 将期望在数据库中为每个类及其子类创建一个单独的表。从它们中选择数据时,您将不得不使用 SQL JOIN 运算符。

数据库架构示例:

CREATE TABLE user {
  id INT,
  name VARCHAR,
  birthday DATE
}
CREATE TABLE employee {
  id INT,
  occupation VARCHAR,
  salary INT,
  join DATE
}
CREATE TABLE client {
  id INT,
  address VARCHAR
}

如果您决定从表中获取某些客户端的数据,那么 Hibernate 将不得不使用 JOIN 来连接表:

SELECT u.id, u.name, u.birthday, c.address FROM user u JOIN client c ON u.id = c.id;

@PrimaryKeyJoinColumn

子实体类在表中有一列引用父实体类的对象 ID。此列的名称默认等于父类的列的名称。

例子:

@Inheritance(strategy = InheritanceType.JOINED)
@Entity
class User {
  @Id
  int user_identifier;
  String name;
  LocalDate birthday;
}
@Entity
class Employee extends User {
 	String occupation;
 	int salary;
 	LocalDate join;
}
@Entity
class Client extends User {
   String address;
}

然后数据库表将如下所示:

CREATE TABLE user {
  user_identifier INT,
  name VARCHAR,
  birthday DATE
}
CREATE TABLE employee {
  user_identifier INT,
  occupation VARCHAR,
  salary INT,
  join DATE
}
CREATE TABLE client {
  user_identifier INT,
  address VARCHAR
}

如果要覆盖依赖表中的列名,则需要使用@PrimaryKeyJoinColumn注解 。例子:

@Inheritance(strategy = InheritanceType.JOINED)
@Entity
class User {
  @Id
  int user_identifier;
  String name;
  LocalDate birthday;
}
@Entity
@PrimaryKeyJoinColumn(name=”user_id”)
class Employee extends User {
 	String occupation;
 	int salary;
 	LocalDate join;
}
@Entity
@PrimaryKeyJoinColumn(name=”user_id2”)
class Client extends User {
   String address;
}

然后数据库表将如下所示:

CREATE TABLE user {
  user_identifier INT,
  name VARCHAR,
  birthday DATE
}
CREATE TABLE employee {
  user_id INT,
  occupation VARCHAR,
  salary INT,
  join DATE
}
CREATE TABLE client {
  user_id2 INT,
  address VARCHAR
}