Description
The next approach to storing a class hierarchy is to store all the classes in the hierarchy in a single table . This strategy is called Single Table .
For example, like this:
CREATE TABLE user_ employee_client {
id INT,
name VARCHAR,
birthday DATE,
occupation VARCHAR,
salary INT,
join DATE,
address VARCHAR,
DTYPE VARCHAR
}
That is, we have one table, in which the columns for all classes of our hierarchy are marked with different colors. There is also a special service column DTYPE VARCHAR , where Hibernate will store the name of the Entity class.
The only thing left to do is to explain to Hibernate that the data of Entity classes is now stored in the database in one table. This can be done using the @Inheritance annotation :
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
An example of our classes:
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@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;
}
How data is stored
Now let's write an example where we create a couple of our entities and save them to the database:
Employee employee = new Employee();
employee.id = 101;
employee.name = "Ivanov";
employee.birthday = LocalDate.of("01-01-1999");
employee.occupation = "Programmer"
employee.salary = 100000;
employee.join = LocalDate.of("12-01-2018");
session.persist(employee);
Client client = new Client();
client.id = 102;
client.name = "Petrov";
client.birthday = LocalDate.of("15-11-1988");
client.address = "Shandara";
session.persist(client);
When saving to the database, the following SQL query will be executed:
INSERT INTO user_ employee_client (id, name, birthday, occupation, salary, join, DTYPE)
VALUES (101, 'Ivanov', '01-01-1999', 'Programmer', 100000, '12-01-2018', 'Employee')
INSERT INTO user_ employee_client (id, name, birthday, address, DTYPE)
VALUES (102, 'Petrov', '15-11-1988', 'Shandara', 'Client')
When saving data to a table, Hibernate passes only entity fields known to it. This means that unspecified columns will be NULL.
And this means that you cannot specify the type NOT NULL for the occupation column, since when a client is stored in the same table, his occupation will be NULL. This is one of the disadvantages of storing different entities in the same table.
The last field in the SQL query is the DTYPE column, which contains the name of the Entity class. It is used by Hibernate when you want to read data from your table.
Example:
List<User> accounts = session.createQuery("from User").list();
This query will return a list of all user-type objects stored in the database: User, Employee, and Client. Based on the DTYPE column, the entity type will be correctly determined and an object of the correct class will be created.
In our case, there will be two objects in the accounts list: an Employee type and a Client type.
HQL rules.
GO TO FULL VERSION