Framework/Nest.js

6. Nest.js, typeorm으로 MySql 사용하기

oniri1 2024. 9. 20. 21:19

0. 설치

npm i @nestjs/typeorm mysql2

1. 데이터 베이스 엔티티(테이블) 생성

src/entity 폴더 생성
테이블명.entitiy.ts 파일 생성 이후 작성

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn({ type: 'int', unsigned: true }) //PrimaryGeneratedColumn은 primaryKey를 뜻한다.
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;

  @Column()
  age: number;
}

Column 데코레이터 안에는 여러 옵션을 줄 수 있다.

    type: 'varchar',
    length: 100,
    nullable: false,
    default: false,
    unique: true,

2.모듈에서 import

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

@Module({
imports: [
        TypeOrmModule.forRootAsync({ //MySQL을 사용하기 위한 설정
            imports: [ConfigModule], // ConfigModule을 import하여 사용할 수 있도록 설정
            inject: [ConfigService], // ConfigService를 주입
            useFactory: async (configService: ConfigService) => ({
            type: 'mysql', // 데이터베이스 유형
            host: configService.get<string>('DB_HOST'), // 데이터베이스 호스트
            port: configService.get<number>('DB_PORT'), // 데이터베이스 포트
            username: configService.get<string>('DB_USER'), // 데이터베이스 사용자 이름
            password: configService.get<string>('DB_PW'), // 데이터베이스 비밀번호
            database: configService.get<string>('DB_NAME'), // 사용할 데이터베이스 이름
            entities: [User], // 엔티티 정의
            synchronize: configService.get<boolean>('IS_DEV'), //nest와 DB 동기화 여부
            logging: configService.get<boolean>('LOG_ENABLE'),//로그 출력 여부
            retryAttempts: 1,//DB 연결 시도횟수
            }),
        }),
        TypeOrmModule.forFeature([User]), //사용할 DB의 테이블을 정확히 정의
    ],
controllers: [UserController],
providers: [UserService],
})
export class AppModule {}

3. service에서 접근

import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()

export class UserService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>, // User 엔티티에 대한 Repository 주입
    ) {}
}


이후

await this.userRepository.save(user);
await this.userRepository.findOneBy({ id });
await this.userRepository.find();
await this.userRepository.delete(id);
await this.userRepository.update(id, userData);

등으로 해당 DB에 접속할 수 있다.

User 생성

const user = new User();
user.name = 'hamster';
user.email = 'hamsterking@naver.com';
user.intro = '저는 햄스터 킹 입니다.';
await this.userRepository.save(user);

관계 맺기

1:1

import { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn } from 'typeorm';

@Entity()
export class User {
  @OneToOne(() => Profile)
  @JoinColumn()
  profile: Profile;
}

@Entity()
export class Profile {
  @OneToOne(() => User, user => user.profile)
  user: User;
}

1:n

import { Entity, Column, PrimaryGeneratedColumn, OneToMany, ManyToOne } from 'typeorm';

@Entity()
export class User {
  @OneToMany(() => Post, post => post.user)
  posts: Post[];
}

@Entity()
export class Post {
  @ManyToOne(() => User, user => user.posts)
  user: User;
}

n:n

import { Entity, Column, PrimaryGeneratedColumn, ManyToMany, JoinTable } from 'typeorm';

@Entity()
export class Student {
  @ManyToMany(() => Course, course => course.students)
  @JoinTable()
  courses: Course[];
}

@Entity()
export class Course {
  @ManyToMany(() => Student, student => student.courses)
  students: Student[];
}

'Framework > Nest.js' 카테고리의 다른 글

8. Nest.js 배포시 주의할 점  (0) 2024.09.20
7. Nest.js, mongoose로 mongoDB 사용하기  (0) 2024.09.20
5. Nest.js, env 적용하기  (0) 2024.09.20
4. Nest.js, Cors 설정  (0) 2024.09.20
3. Nest.js nodemon을 적용시키자  (0) 2024.09.20