TypeORM 통합 기초
NestJS에서 TypeORM을 설정하고 엔터티를 정의하며 저장소를 사용하여 기본적인 데이터베이스 작업을 수행합니다.
TypeORM 통합 기초은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to TypeORM in NestJS
Welcome to integrating TypeORM with NestJS! TypeORM is an Object-Relational Mapper (ORM) that helps you work with databases using TypeScript or JavaScript.
Instead of writing raw SQL queries, you interact with your database using familiar object-oriented programming concepts like classes and objects.
Why Use an ORM?
ORMs like TypeORM offer several benefits:
- Abstraction: No need to write complex SQL.
- Type Safety: With TypeScript, your database interactions are type-checked.
- Portability: Easily switch between different database systems (PostgreSQL, MySQL, SQLite, etc.).
- Productivity: Faster development with less boilerplate code.
Setting Up TypeORM Module
First, we need to install TypeORM and the database driver for your chosen database (e.g., pg for PostgreSQL, sqlite3 for SQLite).
Then, we configure the TypeOrmModule in your main application module (usually AppModule) to establish the database connection.
TypeOrmModule Configuration
Here's how you might configure TypeORM in your app.module.ts. This example uses SQLite for simplicity, which stores data in a file.
We use TypeOrmModule.forRoot() to set up the connection globally.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'db.sqlite',
entities: [], // We'll add our entities here soon!
synchronize: true, // Auto-create tables (dev only!)
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
Defining Your First Entity
An Entity is a class that maps directly to a database table. Each instance of the entity class represents a row in that table.
We use decorators like @Entity(), @PrimaryGeneratedColumn(), and @Column() to define the table and its columns.
User Entity Example
Let's create a simple User entity. This will map to a user table in our database.
@PrimaryGeneratedColumn()creates an auto-incrementing primary key.@Column()defines a regular column.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
}Registering Entities in Module
After defining your entity, you need to tell TypeORM about it. Update your AppModule's TypeOrmModule.forRoot() configuration to include your new User entity.
This allows TypeORM to create the corresponding table in your database.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity'; // Import your entity
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'db.sqlite',
entities: [User], // Register your User entity here
synchronize: true,
}),
],
controllers: [],
providers: [],
})
export class AppModule {}Introducing Repositories
TypeORM Repositories are objects that provide methods for interacting with a specific entity's table in the database.
You inject a repository into your NestJS service (e.g., UserService) to perform CRUD operations (Create, Read, Update, Delete).
Basic Operations: Create & Read
To use a repository, you inject it using @InjectRepository(). Let's see how to create a new user and retrieve all users.
save(): Inserts a new record or updates an existing one.find(): Retrieves all records for the entity.
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
async createUser(): Promise<User> {
const newUser = this.usersRepository.create({
firstName: 'Coddy',
lastName: 'Kit',
isActive: true,
});
return this.usersRepository.save(newUser);
}
async findAll(): Promise<User[]> {
return this.usersRepository.find();
}
}TypeORM Quick Check
Which decorator is used to mark a class as an entity that maps to a database table in TypeORM?
Recap: TypeORM Basics
You've learned the basics of integrating TypeORM into your NestJS application!
- We configured
TypeOrmModulein ourAppModule. - We defined an Entity using decorators like
@Entity(),@PrimaryGeneratedColumn(), and@Column(). - We understood how to use Repositories to perform basic database operations like creating and reading records.
Next, you'll explore more advanced CRUD operations and data handling techniques!
자주 묻는 질문
“TypeORM 통합 기초” 강의는 무료인가요?
네 — “TypeORM 통합 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.
“TypeORM 통합 기초”에서 뭘 배우나요?
NestJS에서 TypeORM을 설정하고 엔터티를 정의하며 저장소를 사용하여 기본적인 데이터베이스 작업을 수행합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.
“TypeORM 통합 기초” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 의존성 주입 이해
- DTO와 유효성 검사 파이프
- TypeORM 통합 기초