Descrizione
Un'altra strategia per memorizzare una gerarchia di classi in un database è chiamata tabella unita. C'è un'annotazione speciale per questo:
@Inheritance(strategy = InheritanceType.JOINED)
Un esempio delle nostre classi:
@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;
}
Quando si utilizza questa annotazione, Hibernate si aspetterà una tabella separata nel database per ogni classe e le sue sottoclassi. Quando si selezionano i dati da essi, sarà necessario utilizzare l'operatore SQL JOIN.
Esempio di schema del database:
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
}
Se decidi di ottenere i dati di alcuni client dalla tabella, Hibernate dovrà utilizzare JOIN per unire le tabelle:
SELECT u.id, u.name, u.birthday, c.address FROM user u JOIN client c ON u.id = c.id;
@PrimaryKeyJoinColumn
Le classi di entità figlio hanno una colonna nella tabella che fa riferimento all'ID oggetto della classe di entità padre. Il nome di questa colonna è per impostazione predefinita uguale al nome della colonna della classe genitore.
Esempio:
@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;
}
Quindi la tabella del database sarà simile a questa:
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
}
Se si desidera sovrascrivere il nome della colonna nelle tabelle dipendenti, è necessario utilizzare l' annotazione @PrimaryKeyJoinColumn . Esempio:
@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;
}
Quindi la tabella del database sarà simile a questa:
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
}