Embedded entities offer a powerful technique to minimize code duplication within your application by utilizing composition over inheritance. Through the use of embedded columns, you can define a class with its own columns and seamlessly integrate these columns into the database table of the current entity. This approach proves particularly effective when dealing with multiple entities that share common properties, such as first name and last name.
Here’s a step-by-step illustration of how to implement and utilize embedded entities:
Step 1: Define Shared Columns in an Embedded Class Create a separate class to house the commonly shared columns, such as first name and last name:
import { Column } from "typeorm"
export class Name {
@Column()
first: string
@Column()
last: string
}
Step 2: Implement Embedded Entities in Individual Entities In each entity that needs the shared columns, utilize the embedded class as a column. This integrates the shared columns into the entity’s database table:
User Entity:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
import { Name } from "./Name"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: string
@Column(() => Name)
name: Name
@Column()
isActive: boolean
}
Employee Entity:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
import { Name } from "./Name"
@Entity()
export class Employee {
@PrimaryGeneratedColumn()
id: string
@Column(() => Name)
name: Name
@Column()
salary: number
}
Student Entity:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
import { Name } from "./Name"
@Entity()
export class Student {
@PrimaryGeneratedColumn()
id: string
@Column(() => Name)
name: Name
@Column()
faculty: string
}
Step 3: Reduced Code Duplication The shared columns defined in the Name
entity will be automatically integrated into each of the individual entity tables, resulting in the following table structures:
User Table:
id | nameFirst | nameLast | isActive |
---|---|---|---|
int(11) | varchar(255) | varchar(255) | boolean |
PRIMARY KEY | |||
AUTO_INCREMENT |
Employee Table:
id | nameFirst | nameLast | salary |
---|---|---|---|
int(11) | varchar(255) | varchar(255) | int(11) |
PRIMARY KEY | |||
AUTO_INCREMENT |
Student Table:
id | nameFirst | nameLast | faculty |
---|---|---|---|
int(11) | varchar(255) | varchar(255) | varchar(255) |
PRIMARY KEY | |||
AUTO_INCREMENT |
Please note that in this representation, the headers are displayed at the top of each table, and the corresponding data types are listed below them. The PRIMARY KEY and AUTO_INCREMENT properties are indicated under their respective columns. This format provides a visual overview of the structure of each table, including the relationships between columns and their associated data types.