Creating entities and tables using decorators in TypeORM is a fundamental aspect of defining your data model and database schema. TypeORM is an Object-Relational Mapping (ORM) library that enables you to define your database structure using TypeScript classes and decorators, making it easier to work with databases in a more object-oriented manner.
Here’s how you can create entities and tables using decorators in TypeORM:
- Entity Definition: An entity represents a database table. It’s essentially a TypeScript class that maps to a table in your database. You define an entity by creating a TypeScript class and decorating it with the
@Entity()
decorator.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
}
- Columns and Primary Key: Inside the entity class, you define the properties (fields) that correspond to the columns in the database table. Each property is decorated with various decorators to define its behavior and data type. For example,
@PrimaryGeneratedColumn()
is used for primary keys that are auto-generated. - Decorators: TypeORM provides various decorators that you can use to define properties:
@PrimaryGeneratedColumn()
: Auto-generates a primary key.@Column()
: Defines a regular column.@CreateDateColumn()
: Auto-populates a timestamp column on entity creation.@UpdateDateColumn()
: Auto-updates a timestamp column on entity updates.@VersionColumn()
: Used for optimistic concurrency control.@ManyToOne()
,@OneToMany()
,@ManyToMany()
: Define relationships between entities.
- Table Name: By default, TypeORM uses the class name to determine the table name. However, you can customize the table name using the
@Entity()
decorator’sname
property.
@Entity({ name: 'custom_users' })
export class User {
// …
}
- Generated SQL Schema: When you run TypeORM’s migration commands, it generates SQL scripts to create or update the database schema based on your entity definitions. These migrations handle the creation of tables, columns, and relationships.
- Running Migrations: After defining your entities, you need to run migrations to apply these changes to the database. TypeORM provides commands to generate migration scripts based on changes in your entities and to apply these scripts to your database.
Command to generate migrations:ON TYPEORM CLI
npx typeorm migration:generate -n InitialMigration
npx typeorm migration:run
Defining entities using decorators simplifies the process of setting up your database schema, as you don’t need to write raw SQL queries. Instead, you define your data model using TypeScript classes and decorators, and TypeORM takes care of translating this into SQL statements for creating tables and columns.