คำอธิบาย

อีกกลยุทธ์หนึ่งสำหรับการจัดเก็บลำดับชั้นของคลาสในฐานข้อมูลเรียกว่าตารางที่เข้าร่วม มีคำอธิบายประกอบพิเศษสำหรับมัน:

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

@PrimaryKeyเข้าร่วมคอลัมน์

คลาสเอนทิตีย่อยมีคอลัมน์ในตารางที่อ้างถึงรหัสวัตถุของคลาสเอนทิตีหลัก โดยค่าเริ่มต้น ชื่อของคอลัมน์นี้จะเท่ากับชื่อของคอลัมน์ของคลาสพาเรนต์

ตัวอย่าง:

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