일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- codingtest
- Linux
- input태그
- 목록
- JAVA11
- 시큐리티 로그아웃
- 리눅스
- 소스트리
- 2차원배열
- 시큐리티
- 싱글톤
- 프로그래머스
- 로그인
- 시큐리티로그인
- 시큐리티 로그인
- programmers
- 반복문
- html
- springboot
- gradle
- Spring boot
- sql
- StyleSheet
- java
- javascript
- security
- 코딩테스트
- springSecurity
- 스프링 부트
- css
Archives
- Today
- Total
JAVAIARY
Spring Boot) 서비스 계층과 DTO 본문
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에 추가되는 것 확인
'Project > 2023.02~ ) Study toy 프로젝트' 카테고리의 다른 글
N:1(다대일) 연관관계 1 (0) | 2023.03.01 |
---|---|
검색 처리 (0) | 2023.02.27 |
Spring Boot) 게시글 수정/ 삭제 처리 (0) | 2023.02.21 |
Spring Boot) 게시글 등록 페이지 / 등록 처리 (0) | 2023.02.20 |
Spring Boot) 목록처리 (0) | 2023.02.20 |