Junior — Middle
What approaches to inheritance in object mapping in Hibernate are you familiar with?
sobes.tech AI
Answer from AI
In Hibernate, there are three main approaches to inheritance mapping of objects to database tables:
-
Single Table (One table per hierarchy)
- All subclass classes are stored in one table.
- A special discriminator column is used to determine the object type.
- Pros: simplicity, high performance during queries.
- Cons: many nullable columns, possible redundancy.
-
Joined (Joined tables)
- Each class has its own table.
- Tables are linked by a key (JOIN).
- Pros: normalized structure, less duplication.
- Cons: complex JOIN queries, potentially slower.
-
Table per Class (Table per class)
- Each class has its own table with fields from all parent classes.
- UNION is used during selection.
- Pros: simple table structure.
- Cons: data duplication, complex queries.
Example annotation for Single Table:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Animal { ... }
@Entity
@DiscriminatorValue("Dog")
public class Dog extends Animal { ... }
The choice of approach depends on performance requirements and data structure.