본문 바로가기
STUDY/LIBRARY

타입 ORM (Type ORM ,Object Relational Mapping)

by bottlesun 2023. 1. 3.
728x90

Type ORM (Object Relational Mapping) 이란?

Type ORM 은 NodeJS, Browser, Cordova, PhoneGap 등의 다양한 플랫폼에서 JS , TS와 함께 사용 할 수 있는 ORM 라이브러리 이다.

다른 ORM 과 달리 액티브 레코드 패턴 (Active Record Pattern) 과 데이터 매퍼 패턴(Data Mapper Pattern) 을 모두 지원하고, 작성할 수 있다.

액티브 레코드 패턴 (Active Record Pattern) 이란?

활성 레코드 접근 방식을 사용해, 모든 쿼리 메서드를 정의하고 모델 메서드를 사용하여 개체를 CRUD(생성, 조회,수정,삭제) 를 한다.

쉽게 말해서 모델 내에서 데이터베이스에 액세스 접근하는 방식이다.

User 모델의 Entity 정의 를 한 예제 이다.

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
}

모든 활성 레코드 엔티티는 BaseEntity 로 확장하여 사용 해야한다.

// 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.findBy({ isActive: true })
const timber = await User.findOneBy({ firstName: "Timber", lastName: "Saw" })

//구현한 메서드
const timber = await User.findByName("Timber", "Saw")

위 User 모델을 이용하여, user 객체에 데이터의 CRUD 를 쉽게 할 수 있게 된다.

데이터 매퍼 패턴(Data Mapper Pattern) 이란?

레퍼지토리 라는 별도의 클래스에서 모든 쿼리 메서드를 정의하고 레포지토리를 사용해, CRUD 를 하게 된다.

액티브 레코드 패턴과 다르게 속성을 정의하고 더미 메서드가 있을 수도 있다.

모델이 아닌 레포지토리 에서 데이터베이스에 접근하는 방식이다.

const userRepository = dataSource.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.findBy({ isActive: true })
const timber = await userRepository.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
}

ORM (Object Relational Mapping) 이란?

객체와 관계형 데이터베이스의 데이터를 자동으로 변형 및 연결 하는 작업이다.

ORM을 이용한 개발은 객체와 데이터베이스의 변형에 유연하게 사용할 수 있다.

TypeORM Code

const boards = Board.find({title:'Hello' , states:'PUBLIC'})

Pure JS Code

db.query('Select * FROM boards WHERE title = "hello" AND status = "PUBLIC"',
 (err, res) => {
  if(err){
    throw new Error('Error')
  } 
  boards = result.rows;
})

Type ORM 특징과 이점

  • 모델을 기반으로 데이터베이스 테이블 체계를 자동으로 생성
  • 데이터 베이스에서 개체를 쉽게 삽입, 업데이트 및 삭제 할 수 있다.
  • 테이블 간 매핑 (일대일, 일대다, 다대다) 을 만든다.
  • 간단한 CLI 명령을 제공

TypeORM 은 간단한 코딩으로 ORM 프레임 워크를 사용하기 쉽다.

TypeORM 은 다른 모듈과 쉽게 통합이 된다.

728x90

댓글