13강. 서비스레이어 책등록 완료
- 책등록 코드 구현
- 서비스 단에 아래와 같이 코딩을 하면 문제점이 있다.
@Service
@RequiredArgsConstructor
public class BookService {
private final BookRepository bookRepository;
public Book 책등록하기(BookSaveReqDto dto) {
Book bookPS = bookRepository.save(dto.toEntity());
return bookPS;
}
1. DTO관련 설명
- 위 bookPS는 영속화된 객체이다. Book 모델이 다른 모델과 연관관계를 가지게 되는 경우 아래와 같은 문제가 발생할 수 있다.
- 영속화된 객체를 컨트롤러단까지 응답하게 되면 컨트롤러 단에서 Spring에 있는 open-in-view가 지연로딩(lazy loading)을 하게 해준다.
- lazy loading을 하게되면 컨트롤러단에서 수많은 변수가 일어날 수 있다.
- 따라서 데이터를 dto로 주고 받아서 영속화된 객체는 서비스단에서 절대 빠져나가지 못하게 해야 한다.
2. DTO 구현
package com.thekim12.junitproject.web.dto;
import com.thekim12.junitproject.domain.Book;
public class BookRespDto {
private Long id;
private String title;
private String author;
public BookRespDto toDto(Book bookPS) {
this.id = bookPS.getId();
this.title = bookPS.getTitle();
this.author = bookPS.getAuthor();
return this;
}
}
- 위와 같이 구현하는 경우 아래처럼 새로운 객체를 만들어서 사용해야 된다는 단점이 있다.
BookRespDto dto = new BookRespDto();
dto.toDto(book);
- 다른 방법으로 static함수로 만드는 방법이 있다. 이것은 메모리에 띄워지는게 단점이다.
public static BookRespDto toDto(Book bookPS) {
BookRespDto dto = new BookRespDto();
dto.id = bookPS.getId();
dto.title = bookPS.getTitle();
dto.author = bookPS.getAuthor();
return dto;
}
- 위 설명을 그림으로 표현한것
