Opis

Inną strategią przechowywania hierarchii klas w bazie danych jest tabela połączona. Jest na to specjalna adnotacja:

@Inheritance(strategy = InheritanceType.JOINED)

Przykład naszych zajęć:

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

Używając tej adnotacji, Hibernate będzie oczekiwał oddzielnej tabeli w bazie danych dla każdej klasy i jej podklas. Wybierając z nich dane, będziesz musiał użyć operatora SQL JOIN.

Przykład schematu bazy danych:

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
}

Jeśli zdecydujesz się pobrać dane jakiegoś klienta z tabeli, Hibernate będzie musiał użyć JOIN, aby dołączyć do tabel:

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

@PrimaryKeyJoinColumn

Klasy Entity podrzędne mają kolumnę w tabeli, która odnosi się do identyfikatora obiektu nadrzędnej klasy Entity. Nazwa tej kolumny jest domyślnie równa nazwie kolumny klasy nadrzędnej.

Przykład:

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

Wtedy tabela bazy danych będzie wyglądać następująco:

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
}

Jeśli chcesz zastąpić nazwę kolumny w tabelach zależnych, musisz użyć adnotacji @PrimaryKeyJoinColumn . Przykład:

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

Wtedy tabela bazy danych będzie wyglądać następująco:

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
}