[index]
▷ Cotroller
▷ Service
▷ Repository
▷ 사용 예제
DDD(Domain-Driven Design)를 사용하면서
일반적으로 만나게 되는 아키텍처의 주요 구성 요소인
Controller, Service, Repository의 역할을 공부할 것이다.
cf) 기본적으로 MVC패턴에서의 Model 부분은
도메인 로직과 데이터 액세스를 다룬다.
도메인 로직은 Service로 나타내고
데이터 액세스는 Repository로 나타낸다.
Controller
단어 그대로 제어하는 것.
DDD에서 제어를 담당하는 역할에 대한 클래스 명칭이다.
Client와 View와 Model 사이에서 데이터의 흐름에 대해 제어해주어,
Controller를 제외한 Client, View, Model이 각자의 역할을 잘 할 수 있도록 해준다.
[역할]
HTTP 요청을 받아 처리하고
응답을 반환하는 역할을 담당한다.
[책임]
Client로부터의 요청을 분석하고,
적절한 서비스 메서드를 호출하며,
응답 데이터를 반환한다.
Service
[역할]
비즈니스 로직을 수행한다.
비즈니스 로직이란 도메인의 규칙과 연산을 의미한다.
[책임]
필요한 비즈니스 연산과 규칙을 구현하며,
저장소에서 데이터를 가져오거나 변환하는 작업을 수행한다.
Repository
[역할]
도메인 객체와 데이터베이스 사이의 연결 역할을 하며,
CRUD 작업을 수행하는 인터페이스를 제공한다.
도메인 객체의 저장과 조회, 삭제, 수정을 담당한다.
Repository의 역할이 있기에
도메인 로직에서는 데이터베이스와 직접적인 상호작용을 걱정할 필요가 없게 된다.
코드의 응집도를 높이고, 유지보수를 용이하게 한다.
[책임]
데이터베이스와의 상호작용을 추상화하여,
도메인 객체를 저장,조회,삭제,수정을 필요에 따라 한다.
사용 예제
Controller, Service, Repository, Entity를 사용한
상품 단건조회 api
@RestController @RequestMapping("/products") public class ProductController { private final ProductService productService; @Autowired public ProductController(ProductService productService) { this.productService = productService; } @GetMapping("/{id}") public ResponseEntity<Product> getProduct(@PathVariable Long id) { Product product = productService.getProductById(id); return ResponseEntity.ok(product); } }
@Service public class ProductService { private final ProductRepository productRepository; @Autowired public ProductService(ProductRepository productRepository) { this.productRepository = productRepository; } public Product getProductById(Long id) { return productRepository.findById(id).orElseThrow(() -> new NoSuchElementException("Product not found")); } }
public interface ProductRepository extends JpaRepository<Product, Long> { }
@Entity @Data public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double price; }
* 개인적으로 구글링하며 기록 중
예제는 일단 검색의 도움을 받아 작성했다..
스스로 작성할 수 있는 그날까지!! 이해하는 데는 시간을 좀 더 투자할 것이다.
'개인 공부 (23.07~' 카테고리의 다른 글
[REST API] 개념, 특징, URI 규칙 이해하기 (0) | 2023.08.15 |
---|---|
MVC 패턴 쉽게 이해하기 (0) | 2023.08.15 |
Entity, Domain, DTO, VO, DAO, Repository 정리 (0) | 2023.08.10 |
[ DDD & SQL 중심 설계(SQL-DD) ] 정의와 비교 (1) | 2023.08.09 |
@RequestParam @PathVariable @RequestBody @ModelAttribute 간단 정리 (0) | 2023.08.06 |