Entities

An entity is a class that maps to a database table, with decorated columns.

Syntax@Entity() / @Column()

An entity is a class that TypeORM maps to a database table. Each decorated property becomes a column.

Key decorators

  • @Entity() - marks the class as a table.
  • @PrimaryGeneratedColumn() - an auto-incrementing primary key.
  • @Column() - a regular column, with options for type, length, and nullability.

Register your entities in TypeOrmModule.forFeature([User]) inside the feature module that uses them.

Example

Example · typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @Column({ default: true })
  isActive: boolean;
}

When to use it

  • A developer decorates a User class with @Entity() and @Column() so TypeORM creates the corresponding users table on startup.
  • A team uses @CreateDateColumn and @UpdateDateColumn to automatically track when records are created or modified without extra code.
  • An engineer defines a @OneToMany relationship on a User entity and @ManyToOne on an Order entity to model a one-to-many database relationship.

More examples

Basic entity

Defines a User entity with an auto-generated primary key, string columns, and a unique constraint on email.

Example · ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity('users')
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @Column({ default: true })
  isActive: boolean;
}

Timestamps and nullable column

Adds automatic timestamp columns and a nullable optional body column to show common real-world entity patterns.

Example · ts
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';

@Entity()
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column({ nullable: true })
  body?: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

One-to-many relationship

Defines a one-to-many relationship so each User can have multiple Orders, linked via a foreign key on the Order side.

Example · ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Order } from '../orders/order.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column() name: string;

  @OneToMany(() => Order, (order) => order.user)
  orders: Order[];
}

Discussion

  • Be the first to comment on this lesson.