스프링부트 요청시 전체 흐름

wsung·2025년 12월 9일

파일 구조 정리해보기


1. 요청 흐름 (클라이언트 → DB)

Controller

Service

DataHandler

DAO

Repository (Spring Data JPA)

DB (MariaDB)


2. 응답 흐름 (DB → 클라이언트)

DB

Repository

DAO

DataHandler

Service

Controller

JSON 응답


레이어하는 일
ControllerHTTP 요청 받기 → Service에 전달, 응답 반환
Service비즈니스 로직, DTO ↔ Entity 변환
DataHandlerService와 DAO 사이에서 데이터 조립
DAORepository 사용해서 DB 작업 처리
RepositoryJPA가 자동으로 만들어주는 DB 쿼리 기능
EntityDB 테이블과 매핑되는 클래스
DTO요청/응답에 사용하는 데이터 객체

실제 동작 예시

예: GET /product/001 호출
1️⃣ Controller

@GetMapping("/product/{productId}")
public ProductDto getProduct(String productId) {
    return productService.getProduct(productId);
}

👉 여기서 productService.getProduct(productId) 호출됨

2️⃣ Service

public ProductDto getProduct(String productId) {
    ProductEntity productEntity = productDataHandler.getProductEntity(productId);
    return new ProductDto(...); // Entity → DTO 변환
}

👉 여기서 Handler 호출

3️⃣ DataHandler

public ProductEntity getProductEntity(String productId) {
    return productDAO.getProduct(productId);
}

👉 DAO 호출

4️⃣ DAO

public ProductEntity getProduct(String productId) {
    return productRepository.getById(productId);
}

👉 Repository로 DB 조회

5️⃣ Repository (Spring JPA)

getById(productId)

👉 DB에서 row 찾아서 ProductEntity 만들어서 반환

6️⃣ 다시 위로 올라옴

⚡ Repository → DAO → Handler → Service

Service가 Entity를 DTO로 변환:

return new ProductDto(
    entity.getProductId(),
    entity.getProductName(),
    entity.getProductPrice(),
    entity.getProductStock()
);

7️⃣ Controller가 JSON 반환

최종 응답:

{
  "productId": "001",
  "productName": "에어팟",
  "productPrice": 300000,
  "productStock": 10
}

🎯 각 파일의 핵심 의도
👑 1) Controller

HTTP 통신 담당
DB를 몰라야 함
필요한 데이터만 받아서 Service에 넘김

🧠 2) Service

비즈니스 로직 담당
Entity ↔ DTO 변환
Handler를 통해 DB 접근

🔧 3) Handler

Service와 DAO를 느슨하게 연결
비즈니스 로직이 DB에 종속되지 않도록 설계

📀 4) DAO

Repository를 사용해서 실제 DB 작업
🧾 5) Repository

JPA가 자동으로 구현
save, findById, getById, delete 등 제공

🧱 6) Entity

DB 테이블과 매핑되는 클래스
@Entity, @Table

📦 7) DTO

API 입출력에 사용되는 객체
JSON ↔ Java 클래스


한눈에 보는 전체 구조

[Controller]
↳ REST API 입구

[Service]
↳ 비즈니스 로직
↳ DTO ↔ Entity 변환

[Handler]
↳ DAO 호출 모으기 (중간 관리자)

[DAO]
↳ Repository 이용해 DB 작업

[Repository]
↳ Spring Data JPA (자동)

[Entity]
↳ DB 테이블 매핑

[DTO]
↳ 클라이언트에게 보여주는 데이터

Q) 왜 이렇게 나누는가?

=> 유지보수 & 확장성이 좋아짐

ex) DB를 MariaDB → MongoDB로 바꾸고 싶다?

=> Controller, Service는 그대로 두고, DAO/Repository만 바꾸면 됨
즉 UI와 DB가 완전히 분리됨


핵심 3줄

  • Controller는 요청만 받는다
  • Service는 로직 + DTO/Entity 변환한다
  • Repository는 DB 저장/조회한다

나의 정리
1. Controller가 Service 호출하며 요청이 시작됨
2. 데이터 종류는 DB의 테이블인 Entity와, http에서 사용하는 DTO 2가지가 존재함 이것을 서로 변환해주는 것이 나의 역할
3. DAO는 DB의 데이터에 접근하는 객체
4. hadler로 service와 DAO를 연결함
5. DAO가 repository에 접근하여 jparepository의 기능을 수행
6. 변환된 데이터 역순으로 올라와서 service에서 DTO로 변환

profile
0부터 시작하는 백엔드

0개의 댓글