Description

Another strategy for storing a class hierarchy in a database is called Joined Table. There is a special annotation for it:

@Inheritance(strategy = InheritanceType.JOINED)

An example of our classes:

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

When using this annotation, Hibernate will expect a separate table in the database for each class and its subclasses. When selecting data from them, you will have to use the SQL JOIN operator.

Database schema example:

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
}

If you decide to get the data of some client from the table, then Hibernate will have to use JOIN to join the tables:

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

@PrimaryKeyJoinColumn

Child Entity classes have a column in the table that refers to the object id of the parent Entity class. The name of this column is by default equal to the name of the column of the parent class.

Example:

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

Then the database table will look like this:

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
}

If you want to override the column name in dependent tables, then you need to use the @PrimaryKeyJoinColumn annotation . Example:

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

Then the database table will look like this:

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
}
undefined
1
Task
Module 4. Working with databases, level 15, lesson 3
Locked
Joined Table Strategy
task1503