説明

クラス階層をデータベースに格納するための別の戦略は、結合テーブルと呼ばれます。これには特別な注釈があります。

@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
}