JAVAIARY

Spring Boot) 서비스 계층과 DTO 본문

Project/2023.02~ ) Study toy 프로젝트

Spring Boot) 서비스 계층과 DTO

shiherlis 2023. 2. 20. 16:55

DTO 방식

  • 엔티티 객체와 달리 각 계층끼리 주고받는 우편물, 상자의 개념
  • 읽기, 쓰기 모두 허용
  • 일회성
  • JPA와는 생명주기도 다르기 때문에 분리해서 처리하는 것을 권장
  • 장점
    • entity 객체의 범위를 한정 지을 수 있기 떄문에 더 안전한 코드 작성 가능
    • 화면과 데이터를 분리하려는 취지에 부합
  • 단점
    • entity와 유사한 코드를 중복 코딩
    • 엔티티 ↔ DTO 변환 과정 필요

1. 클래스 생성

dto 패키지에 GuestbookDTO 클래스, service 패키지 GuestbookService 인터페이스, GuestbookServiceImpl 클래스 생성

 

package com.example.demo.service;

import com.example.demo.dto.GuestbookDTO;
import com.example.demo.entity.Guestbook;

public interface GuestbookService {
    Long register(GuestbookDTO dto);
}
package com.example.demo.service;

import com.example.demo.dto.GuestbookDTO;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

@Service
@Log4j2
public class GuestbookServiceImpl {

    public Long register(GuestbookDTO dto){
        return null;
    }
}

2.  등록 & DTO → 엔티티 변환

  • 기존에 만든 DTO와 엔티티 클래스를 유지하기 위해 GuestbookService 인터페이스에 default 메서드를 이용하여 처리
package com.example.demo.service;

import com.example.demo.dto.GuestbookDTO;
import com.example.demo.entity.Guestbook;

public interface GuestbookService {
    Long register(GuestbookDTO dto);

    default Guestbook dtoToEntity(GuestbookDTO dto){
        Guestbook entity = Guestbook.builder()
                .gno(dto.getGno())
                .title(dto.getTitle())
                .content(dto.getContent())
                .writer(dto.getWriter())
                .build();
        return entity;
    }
}
  • 인터페이스 내에 default 기능을 활용해 구현클래스에서 동작할 수 있는 dtoToEntity()구성

Tests

package com.example.demo.service;

import com.example.demo.dto.GuestbookDTO;
import com.example.demo.entity.Guestbook;
import com.example.demo.repository.GuestbookRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

@Service
@Log4j2
@RequiredArgsConstructor
public class GuestbookServiceImpl implements GuestbookService{
    private final GuestbookRepository repository;   // 반드시 final로 선언
    @Override
    public Long register(GuestbookDTO dto){

        log.info("DTO------------------");
        log.info(dto);

        Guestbook entity = dtoToEntity(dto);

        log.info(entity);

        repository.save(entity);
        return null;
    }
}

DB에 추가되는 것 확인