<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.0.0</version>
</dependency>
메이븐으로 프로젝트 업데이트
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
PostServiceImle 클래스
@Service
public class PostServiceImpl implements PostService {
private PostRepository postRepository;
private ModelMapper modelMapper;
// 단일 생성자인 경우는 추가적인 autowired 어노테이션이 필요 없다.
public PostServiceImpl(PostRepository postRepository, ModelMapper mapper) {
this.postRepository = postRepository;
this.modelMapper = mapper;
}
//Entity -> DTO
private PostDto mapToDto(Post post) {
PostDto postResponse = modelMapper.map(post, PostDto.class);
// PostDto postResponse = new PostDto();
// postResponse.setId(post.getId());
// postResponse.setTitle(post.getTitle());
// postResponse.setContent(post.getContent());
// postResponse.setDescription(post.getDescription());
return postResponse;
}
//DTO -> Entity
private Post mapToEntity(PostDto postDto) {
Post post = modelMapper.map(postDto, Post.class);
// Post post = new Post();
// post.setTitle(postDto.getTitle());
// post.setContent(postDto.getContent());
// post.setDescription(postDto.getDescription());
return post;
}
CommentServiceImle에도 똑같이 ModelMapper를 적용하라.