描述
在數據庫中存儲類層次結構的另一種策略稱為 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
}
GO TO FULL VERSION