Olá, estou começando os estudos com Spring Boot, mas estou tendo um problema com minhas entidades ao tentar acessar a url delas.
Aqui está o package explorer package explorer do projeto
A classe CommentController
@RestController
@RequestMapping("/comments")
public class CommentController {
private final CommentService commentService;
@Autowired
public CommentController(CommentService commentService) {
this.commentService = commentService;
}
@GetMapping("/{commentId}")
public ResponseEntity<Comment> getCommentById(@PathVariable Long commentId) {
Comment comment = commentService.getCommentById(commentId);
return ResponseEntity.ok(comment);
}
}
A classe CommentsService
package com.projetoredesocial.service;
@Service
public class CommentService {
@Autowired
private final CommentRepository commentRepository;
public CommentService (CommentRepository commentRepository) {
this.commentRepository = commentRepository;
}
public Comment createComment(Comment comment) {
return commentRepository.save(comment);
}
public List<CommentDTO> getCommentDTOsByPostId(Long postId) {
List<Comment> comments = commentRepository.findAllByPostId(postId);
List<CommentDTO> commentDTOs = new ArrayList<>();
for(Comment comment : comments) {
CommentDTO commentDTO = mapCommentToDTO(comment);
commentDTOs.add(commentDTO);
}
return commentDTOs;
}
//
public CommentDTO mapCommentToDTO(Comment comment) {
CommentDTO commentDTO = new CommentDTO();
commentDTO.setId(comment.getId());
commentDTO.setText(comment.getText());
commentDTO.setCommentDate(comment.getCommentDate());
commentDTO.setUser(comment.getUser());
commentDTO.setPost(comment.getPost());
return commentDTO;
}
public void deleteComment(Long commentId, Long userId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new CommentNotFoundException("Comentário não encontrado"));
if(!comment.getUser().getId().equals(userId)) {
throw new UnauthorizedAccessException("Você não tem permissão para excluir esse comentário");
}
commentRepository.delete(comment);
}
public boolean hasComments(Post post) {
List<Comment> comments = commentRepository.findByPost(post);
return !comments.isEmpty();
}
public Comment getCommentById(Long commentId) {
Optional<Comment> commentOptional = commentRepository.findById(commentId);
if(commentOptional.isPresent()) {
return commentOptional.get();
} else {
throw new CommentNotFoundException("Comentário não encontrado por ID");
}
}
}