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
package com.projetoredesocial.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.projetoredesocial.entity.Comment;
import com.projetoredesocial.service.CommentService;
@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);
}
}
o meu pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.projetoredesocial</groupId>
<artifactId>redesocial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redesocial</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
e minha application.properties
# Configurações do banco de dados PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/RedeSocial
spring.datasource.username=postgres
spring.datasource.password=1234
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.security.enabled=false
server.port=8082
A classe CommentsService
package com.projetoredesocial.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.projetoredesocial.dto.CommentDTO;
import com.projetoredesocial.entity.Comment;
import com.projetoredesocial.entity.Post;
import com.projetoredesocial.exception.CommentNotFoundException;
import com.projetoredesocial.exception.UnauthorizedAccessException;
import com.projetoredesocial.repository.CommentRepository;
@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");
}
}
}
Por último, o código da única que funciona, que eu fiz para testar e até agora não estou entendendo o motivo de essa classe funcionar e as outras não:
package com.projetoredesocial.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class HomeController {
@GetMapping("/index")
public String home() {
return "index";
}
}
EDIT: O erro que aparece é
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Sep 04 14:33:54 BRT 2023
There was an unexpected error (type=Not Found, status=404).