Entity Inheritance

Concrete Table Inheritance

You can reduce duplication in your code by using entity inheritance patterns.The simplest and the most effective is concrete table inheritance.

For example, you have Photo, Question, Post entities:

  1. @Entity()
  2. export class Photo {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column()
  6. title: string;
  7. @Column()
  8. description: string;
  9. @Column()
  10. size: string;
  11. }
  1. @Entity()
  2. export class Question {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column()
  6. title: string;
  7. @Column()
  8. description: string;
  9. @Column()
  10. answersCount: number;
  11. }
  1. @Entity()
  2. export class Post {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column()
  6. title: string;
  7. @Column()
  8. description: string;
  9. @Column()
  10. viewCount: number;
  11. }

As you can see all those entities have common columns: id, title, description.To reduce duplication and produce a better abstraction we can create a base class called Content for them:

  1. export abstract class Content {
  2. @PrimaryGeneratedColumn()
  3. id: number;
  4. @Column()
  5. title: string;
  6. @Column()
  7. description: string;
  8. }
  1. @Entity()
  2. export class Photo extends Content {
  3. @Column()
  4. size: string;
  5. }
  1. @Entity()
  2. export class Question extends Content {
  3. @Column()
  4. answersCount: number;
  5. }
  1. @Entity()
  2. export class Post extends Content {
  3. @Column()
  4. viewCount: number;
  5. }

All columns (relations, embeds, etc.) from parent entities (parent can extend other entity as well)will be inherited and created in final entities.

This example will create 3 tables - photo, question and post.

Single Table Inheritance

TypeORM also supports single table inheritance.Single table inheritance is a pattern when you have multiple classes with their own properties,but in the database they are stored in the same table.

  1. @Entity()
  2. @TableInheritance({ column: { type: "varchar", name: "type" } })
  3. export class Content {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. title: string;
  8. @Column()
  9. description: string;
  10. }
  1. @ChildEntity()
  2. export class Photo extends Content {
  3. @Column()
  4. size: string;
  5. }
  1. @ChildEntity()
  2. export class Question extends Content {
  3. @Column()
  4. answersCount: number;
  5. }
  1. @ChildEntity()
  2. export class Post extends Content {
  3. @Column()
  4. viewCount: number;
  5. }

This will create a single table called content and all instances of photos, questions and postswill be saved into this table.

Using embeddeds

There is an amazing way to reduce duplication in your app (using composition over inheritance) by using embedded columns.Read more about embedded entities here.