新規コメントPOSTの作成

2077 ワード


1.サービス
public interface CommentService {
	// 새 댓글 생성
	CommentDto createComment(Long postId, CommentDto commentDto);
}
2.サービスimpl(インタフェース実装)
@Service
public class CommentServiceImpl implements CommentService{
	
	private CommentRepository commentRepository;
	private PostRepository postRepository;
	
	
	public CommentServiceImpl(CommentRepository commentRepository, PostRepository postRepository) {
		this.commentRepository = commentRepository;
		this.postRepository = postRepository;
	}

	@Override
	public CommentDto createComment(Long postId, CommentDto commentDto) {
		
		Comment comment = mapToEntity(commentDto);
		//ID 로 포스트 찾기 못찾을 경우 예외처리
		Post post = postRepository.findById(postId).orElseThrow(() -> new ResourceNotFoundException("Post", "id", postId));
		
		comment.setPost(post);
		
		Comment newComment = commentRepository.save(comment);
		
		return mapToDTO(newComment);
	}

	//Entity -> DTO
	private CommentDto mapToDTO(Comment comment) {		
		CommentDto commentDto = new CommentDto();
		commentDto.setId(comment.getId());
		?
		return commentDto;
	}
	
	//DTO -> Entity (아이디는 자동생성 됨)
	private Comment mapToEntity(CommentDto commentDto) {
		Comment comment = new Comment();
		comment.setName(commentDto.getName());
		?		
		return comment;
	}
}
3.コントローラ
	@PostMapping("/posts/{postId}/comments")
	public ResponseEntity<CommentDto> createComment(@PathVariable Long postId, @RequestBody CommentDto commentDto ){		
		return new ResponseEntity<>(commentService.createComment(postId, commentDto), HttpStatus.CREATED) ;
	}