Conservation issues

Today we will have a new and super interesting scheme - using the Hibernate features to save the class hierarchy to the database.

A class hierarchy is a set of classes related to each other by an inheritance relationship.

Imagine that you have three classes that you want to store in the database:

class User {
  int id;
  String name;
  LocalDate birthday;
}
class Employee extends User {
 	String occupation;
 	int salary;
 	LocalDate join;
}
class Client extends User {
   String address;
}

Classes are inherited from each other. And the most interesting thing is that you want to use Hibernate in order to store objects of these classes in the database.

Solution types

Hibernate has 4 possible ways that it can associate a class hierarchy with tables in a database:

  • MappedSuperclass
  • single table
  • Joined Table
  • Table per class

Each strategy assumes its own table structure in the database. Sometimes they are quite complex. But queries for HQL to them are very simple. This is exactly the case where the advantages of Hibernate are clearly manifested.

I have never heard these terms translated into Russian, so I also recommend pronouncing them in English.

Below we will analyze what each of them means.

@MappedSuperClass

Let's start with the simplest solution - in the database you have separate tables for each class . For example, these:

CREATE TABLE user {
  id INT,
  name VARCHAR,
  birthday DATE
}
CREATE TABLE employee {
  id INT,
  name VARCHAR,
  birthday DATE,
  occupation VARCHAR,
  salary INT,
  join DATE
}
CREATE TABLE client {
  id INT,
  name VARCHAR,
  birthday DATE,
  address VARCHAR
}

Only you know that the classes for these tables are connected in a hierarchy . If you want Hibernate to know about this too, you need to add the @MappedSuperclass annotation to the parent class . Without it, Hibernate will simply ignore the fields and annotations of the parent class.

Classes with this annotation will look like this:

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

This is the most primitive way of linking the class hierarchy and the database. This approach actually only allows you to avoid duplicate fields in classes.

Database queries in HQL will return only the entity whose type is specified explicitly. You cannot write a database query in HQL and get a list of all users: User, Employee, Client.

undefined
1
Task
Module 4. Working with databases, level 15, lesson 0
Locked
MappedSuperClass Strategy
task1501