Entities & the Repository Pattern

Classes Mapped to Tables, Methods to SQL

Entities & the Repository Pattern

An entity class describes a table. The repository gives you methods to find, save, and delete rows without writing SQL.

4 min read Level 2/5 #nestjs#typeorm#entities
What you'll learn
  • Define an @Entity with @Column decorators
  • Register entities via forFeature
  • Inject a Repository in a service

An entity is a TypeScript class with decorators that tell TypeORM how to map it to a database table. A repository is the object you use to query and persist those entities.

Defining an Entity

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
} from 'typeorm';

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

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

  @Column()
  name: string;

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

  @CreateDateColumn()
  createdAt: Date;
}

The class name (User) becomes the table name (user) by default. You can override with @Entity('users') if you prefer plural table names.

Register the Entity in a Feature Module

forRoot in AppModule configures the connection. Each feature module calls forFeature to expose a repository for the entities it owns.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersService } from './users.service';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

This makes a Repository<User> provider available — but only inside UsersModule. Other modules don’t see it unless UsersModule exports a service that uses it.

Injecting the Repository

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User) private readonly repo: Repository<User>,
  ) {}

  create(email: string, name: string) {
    const user = this.repo.create({ email, name });
    return this.repo.save(user);
  }

  findById(id: number) {
    return this.repo.findOne({ where: { id } });
  }
}

Two things worth noting:

  • repo.create() only builds the object — it does not hit the database. save() is what writes.
  • The repository is a singleton, safe to share across many requests.
Querying With Repositories & QueryBuilder →