안녕하세요. 주니어 백엔드 개발자 입니다.
심바 블로그
안녕하세요. 주니어 백엔드 개발자 입니다.
>> Github 바로가기
  • 분류 전체보기 (31)
    • AWS (3)
    • DATABASE (2)
    • Docker (1)
    • Architecture (3)
    • GraphQL (5)
    • JS (1)
    • NestJS (8)
    • 테스트 코드 (3)
    • 세미나 (4)
    • 기타 (1)
    • 이전 블로그 자료들 (0)

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
안녕하세요. 주니어 백엔드 개발자 입니다.

심바 블로그

DATABASE

Data Mapper 패턴, Active Record패턴

2023. 2. 24. 13:57
반응형

예전에 Sequelize나 TypeORM을 사용하려 공부할 때 여러 가지 패턴으로 엔티티를 구현하는 것을 보고 많이 헷갈렸었다. 그 이후로는 습관적으로 한 가지 방식으로만 사용하고 있다가 나중에 해당 패턴인 Data Mapper 패턴이라는 것을 알았다.

 

- Data Mapper 패턴이란?

 

Data Mapper 패턴은 데이터베이스 모델 (엔티티) 와 쿼리가 분리된 패턴이다.

(데이터베이스에 접근하는 쿼리들을 repository 계층에서 관리)

 

이렇게 역할에 따라서 계층을 나누게 되면 서로 독립적으로 유지될 수 있다는 장점이 있다.

아래 예시 코드를 보면 모든 쿼리는 repository 계층에 모여있고, entity는 다른 계층에 별도의 클래스로 관리되고 있다.

// repository 계층

@Injectable()
export class ReplyCommentsRepository implements IReplyCommentsRepository {
  constructor(@InjectRepository(ReplyComments) private replyCommentsRepository: Repository<ReplyComments>) {}

  async createReplyComment(contents: string, commentId: number, isUser: Users): Promise<ReplyComments> {
    const newReplyComment = this.replyCommentsRepository.create();
    newReplyComment.contents = contents;
    return await this.replyCommentsRepository.save(newReplyComment);
  }

  async deleteReplyComment(replyCommentId: number): Promise<void> {
    await this.replyCommentsRepository.delete({ id: replyCommentId });
    return;
  }
}


////////////////////////////////////////////////////////////////

// entity 선언 계층

@Entity('replyComments')
export class ReplyComments {
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  id: number;

  @Column('varchar', { name: 'contents' })
  contents: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

 


 

- Active Record 패턴

 

해당 패턴은 데이터베이스 엔티티와 쿼리가 같은 클래스에 존재하는 패턴이다. 좀 더 직관적인 장점이 있다고 한다.

 

아래 코드 예시를 보면 entity 클래스가 BaseEntity를 상속 받고, 해당 클래스 내부에 쿼리가 선언되어 있다.

 

@Entity('replyComments')
export class ReplyComments extends BaseEntity{
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  id: number;

  @Column('varchar', { name: 'contents' })
  contents: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
  
  async createReplyComment(contents: string, commentId: number, isUser: Users): Promise<ReplyComments> {
    const newReplyComment = this.replyCommentsRepository.create();
    newReplyComment.contents = contents;
    return await this.replyCommentsRepository.save(newReplyComment);
  }

  async deleteReplyComment(replyCommentId: number): Promise<void> {
    await this.replyCommentsRepository.delete({ id: replyCommentId });
    return;
  }
}

 

 

반응형

'DATABASE' 카테고리의 다른 글

TypeORM에서 불필요한 SELECT 실행  (0) 2023.06.12
    'DATABASE' 카테고리의 다른 글
    • TypeORM에서 불필요한 SELECT 실행
    안녕하세요. 주니어 백엔드 개발자 입니다.
    안녕하세요. 주니어 백엔드 개발자 입니다.

    티스토리툴바