포스트

[TIL] CRUD Code Shadowing 3rd session

This article summarizes the process of separating the controller's business logic into services and applying transactions.

한국어 원문은 여기에서 볼 수 있습니다.
[TIL] CRUD Code Shadowing 3rd session

Separate business logic from Controller

OrderService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.sparta.assignment.order.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;

import com.sparta.assignment.order.dto.OrderRequest;
import com.sparta.assignment.order.dto.OrderResponse;
import com.sparta.assignment.order.entity.Order;
import com.sparta.assignment.order.repository.OrderRepository;
import com.sparta.assignment.prduct.entity.Product;
import com.sparta.assignment.prduct.repository.ProductRepository;

@Service
@RequiredArgsConstructor
public class OrderService {

    private final OrderRepository orderRepository;
    private final ProductRepository productRepository;

    @Transactional
    public OrderResponse createOrder(OrderRequest request) {
        Product product = productRepository.findById(request.getProductId())
                .orElseThrow(() -> new IllegalArgumentException(
                        "해당 상품이 존재하지 않습니다. id=" + request.getProductId()
                ));

        Order order = new Order(product);
        Order saved = orderRepository.save(order);
        OrderResponse orderResponse = new OrderResponse(saved);
        return orderResponse;
    }

    @Transactional(readOnly = true)
    public OrderResponse getOrder(Long id) {
        Order order = orderRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException(
                        "해당 주문이 존재하지 않습니다. id=" + id
                ));
        OrderResponse orderResponse = new OrderResponse(order);
        return orderResponse;
    }

}
  • In the case of the get type method, the Transaction is created as is using @Transactional(readOnly = true), but a hint is given to JPA that no modification will be made (no change detection (dirty checking)).
  • Since the Controller is receiving results in the form of OrderResponse orderResponse = orderService.메서드명, the Service must return the OrderResponse form.