TypeORM Pattern

2020. 10. 2. 18:00DEV/TypeORM

반응형

TypeORM이란?

  • TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large scale enterprise applications with multiple databases.
  • TypeORM supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high quality, loosely coupled, scalable, maintainable applications the most productive way.
  • TypeORM is highly influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.
  • JPA와 유사 기능을 한다고 생각하면 될 듯.

TypeORM Pattern

Active Record vs Data Mapper

  1. Active Record : 작은 규모 애플리케이션에 적합, 간단히 사용 가능
  2. Data Mapper : 규모가 큰 애플리케이션에 적합, 유지/보수가 효과적

Active Record

  • 모델 그 자체에 Query method 정의
  • 모델 메서드를 사용하여 객체 저장/제거/호출
  • baseEntity 클래스를 사용하여 새로운 클래스에 상속 가능

모델 정의

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

@Entity()
export class User extends BaseEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    isActive: boolean;

    // firstName, lastName으로 검색하는 메소드 정의
    static findByName(firstName: string, lastName: string) {
        return this.createQueryBuilder("user")
            .where("user.firstName = :firstName", { firstName })
            .andWhere("user.lastName = :lastName", { lastName })
            .getMany();
    }

}

모델 사용

// example how to save AR entity
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.isActive = true;
await user.save();

// example how to remove AR entity
await user.remove();

// example how to load AR entities
const users = await User.find({ skip: 2, take: 5 });
const newUsers = await User.find({ isActive: true });
const timber = await User.findOne({ firstName: "Timber", lastName: "Saw" });

// example how to use custom static method
const timber = await User.findByName("Timber", "Saw");

Data Mapper

  • 쿼리 메소드를 분리된 클래스에 정의
  • Repository를 이용하여 객체를 저장/제거/호출
  • Active Record Pattern과 다른 점 : 모델이 아닌 Repository에서 데이터에 접근한다는 것

Class 정의

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

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    isActive: boolean;

}

Repository 정의

정의한 클래스를 상속받아 메소드 추가

import {EntityRepository, Repository} from "typeorm";
import {User} from "../entity/User";

@EntityRepository()
export class UserRepository extends Repository<User> {

    findByName(firstName: string, lastName: string) {
        return this.createQueryBuilder("user")
            .where("user.firstName = :firstName", { firstName })
            .andWhere("user.lastName = :lastName", { lastName })
            .getMany();
    }

}

모델 사용

정의된 Model:User로 객체를 생성하고, 정의된 Repository:UserRepository로 메소드 호출

const userRepository = connection.getRepository(User);

// example how to save DM entity
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.isActive = true;
await userRepository.save(user);

// example how to remove DM entity
await userRepository.remove(user);

// example how to load DM entities
const users = await userRepository.find({ skip: 2, take: 5 });
const newUsers = await userRepository.find({ isActive: true });
const timber = await userRepository.findOne({ firstName: "Timber", lastName: "Saw" });

// example how to use static method
const userRepository = connection.getCustomRepository(UserRepository);
const timber = await userRepository.findByName("Timber", "Saw");

DB 생성 방법

1. entity 작성

NestJS 프로젝트에서 entity 작성

2. migrations 확인

  1. pika project > src > migrations
  2. Enter a caption for this image (optional)

[REF]

반응형

'DEV > TypeORM' 카테고리의 다른 글

TypeORM Migration하기  (0) 2020.10.06
TypeORM Relations  (1) 2020.10.04
TypeORM Entity  (0) 2020.10.03