DTO를 효과적으로 사용하기 위해 정적 팩토리 메서드를 활용하려고 합니다.
builder()로 직접 사용하는 대신 정적 메서드를 활용해서 계층 간의 의존성을 줄이자는 것입니다.@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
@Transactional(readOnly = true)
public PostDto findPostById(long postSeq) throws Exception {
final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
-> new NoSuchElementException("cannot found post info with id : " + postSeq));
return PostDto.builder() // 직접 사용
~~~
.createBy(post.getCreateBy())
.build();
}
}
@Transactional(readOnly = true)
public PostDto findPostById(long postSeq) throws Exception {
final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
-> new NoSuchElementException("cannot found post info with id : " + postSeq));
return PostDto.ofEntity(post); //정적 메서드 사용
}
정적 팩토리 메서드를 통해 DTO 생성 의미를 명확하게 전달하고 계층 간 의존성을 줄입니다.
from : 하나의 매개 변수를 받아서 객체를 생성of : 여러 개의 매개 변수를 받아서 객체를 생성getInstance | instance : 인스턴스를 생성. 이전에 반환했던 것과 같을 수 있음.newInstance | create : 새로운 인스턴스를 생성get[OtherType] : 다른 타입의 인스턴스를 생성. 이전에 반환했던 것과 같을 수 있음.new[OtherType] : 다른 타입의 새로운 인스턴스를 생성.mapToEntity: DTO에서 엔티티 생성@Getter
@Builder
@RequiredArgsConstructor
public class PostDto {
private final Long postSeq;
private final String postTitle;
private final String postContent;
private final Date createDate;
private String createBy;
public static PostDto from(PostEntity entity) {
return PostDto.builder()
.postSeq(entity.getPostSeq())
.postTitle(entity.getPostTitle())
.postContent(entity.getPostContent())
.createDate(entity.getCreateDate())
.createBy(entity.getCreateBy()).build();
}
}