MVC 패턴을 공부하며, DAO와 Repository는 비슷한 개념으로 혼용되어 쓰는 줄 알았다.
하지만 차이점을 공부해보니, 비슷하게 보일 뿐 완전 다르다는 것을 알게되었다.
차이점을 알아가보자!
먼저 Repository는 DDD에서 나온 단어라는 것을 알고 가야한다.
그럼 DDD란 무엇일까?
DDD(Domain-Driven-Design)
도메인 주도 설계.
즉 도메인 패턴을 중심에 놓고 설계하는 방식이다.
DDD에서 말하는 도메인이란 비즈니스 도메인으로, 유사한 업무의 집합을 말한다.
예를 들어 이커머스 서비스일 경우, 결제 / 주문 / 배송 / 고객관리 / 인증 등으로 분리할 수 있다.
이처럼 DDD는 큰 규모의 서비스를 작은 비즈니스 단위로 쪼개어 각 도메인 간의 응집도를 높이고, 서로 다른 도메인끼리는 느슨한 의존도를 가질 수 있다.
Repository Pattern
Repository Pattern은 DDD에서 처음 소개된 개념으로, 공통적인 데이터 Access & Manipluate에 집중하여 도메인 모델 계층과 구현 기술을 분리시키는 것을 의미한다.
이렇게 구현함으로써 RDB나 Query같이, 어떠한 구현 기술에 종속적이지 않고 도메인에 더욱 집중할 수 있게 되는 패턴을 의미한다.
즉, Repository는 도메인과 Data source layer 간에 중재자 역할을 수행하는 것이다.
풀어서 설명하자면, Repository는 영속성 장치에서 쿼리의 결과로 받아온 데이터를 도메인에서 사용하기 적합하도록 도메인 객체로 mapping 하는 역할을 수행한다.
DAO와 Repository의 공통점
둘 다 데이터베이스나 기타 영속성 메커니즘 접근을 캡슐화하는 역할을 수행한다.
영속성(persistence): 데이터를 생성한 프로그램의 실행이 종료되더라도 사라지지 않는 데이터의 특성
DAO와 Repository의 차이점
DAO는 DB 테이블과 1대1 매핑을 한다.
하지만 Repository의 생성 기준은 DB 테이블이 아니다.
Repository는 연관이 있고, 함께 변경되어야 하는 여러 도메인 모델 사이에서, 이들의 진입점 역할을 할 수 있는 도메인 엔티티에 대해서만 Repository를 구현한다.
Repository로 다루는 객체를 다루기 위해서 여러 테이블에 접근해야 한다면, 여러 DAO를 사용할 수 있는 것이다.
(도메인 엔티티가 DB 테이블에 1대1 매핑이 된다면, 결국 Repository와 DAO 각각 1개씩 사용하게 되므로 별 차이 X)
관점에 따라 둘의 차이를 정리해보자.
개념
DAO: 데이터에 접근하도록 DB 관련 로직을 모아둔 객체
Repository: Entity 객체를 보관하고 관리하는 저장소
구현
DAO: DB와 가까운 CRUD 로직을 구현할 때 사용
Repository: 객체를 DB와 연결지을 때 사용
연관성
DAO: DB에 조금 더 연관
Repository: 도메인 모델에 조금 더 연관
계층
DAO: DB에 더 가까운 저수준 개념으로, 데이터 매핑/액세스 계층
Repository: 도메인 개체에 더 가까운 상위 수준 개념으로, 도메인과 데이터 액세스 계층 사이
틀린 부분이 있으면 지적해주시면 감사하겠습니다.
Reference
'Server' 카테고리의 다른 글
[JPA] JPA란 / 영속성 컨텍스트 #1 (0) | 2024.08.02 |
---|---|
[JPA] GenerationType.IDENTITY 오류 / AUTO_INCREMENT (0) | 2024.08.02 |
[SpringBoot] 패키지 구조 선택하기 계층형/도메인형 (0) | 2024.07.30 |
[SpringBoot] DTO, DAO, VO 개념 알아보기 (0) | 2024.07.12 |
[SpringBoot] MVC 패턴 (2) | 2024.07.11 |