You need to make a distinction between your controller and your repository. The controller is what is responsible for everything related to HTTP and HTML, so parsing the URL, generating the HTML, etc... The repository is the class that is responsible for querying the database.
A controller would typically look like this:
@Controller
@RequestMapping("/comments")
public class CommentsController {
@GetMapping
public String listAllComments(Model model) {
// Normally, you don't go directly to the repository,
// but use a service in between, but I show it like this
// to make a bit easier to follow
List<Comment> comments = repository.findAll();
model.addAttribute("comments", comments);
return "index"; // This references the Thymeleaf template. By default in a Spring Boot appliation, this would be `src/main/resources/templates/index.html`
}
@GetMapping("/{id}"
public String singleComment(@PathVariable("id") Long id, Model model) {
// Spring will automatically populate `id` with the value of the URL
// Now you can use the id to query the database
Comment comment = repository.findById(id).orElseThrow();
model.addAttribute("comment", comment);
return "single-comment";
}
}
That second method would handle a URL of the form /comments/123
.
In your example, if comments have a category, then most likely, you would use a query parameter, and not a path variable. In that case, your controller method would be:
@GetMapping
public String commentsByCategory(@QueryParameter("categoryId")Long categoryId, Model model) {
List<Comments> comments = repository.findAllByCategoryId(categoryId);
model.addAttribute("comments", comments);
return "comments-by-category";
}
Then the URL would be /comments?categoryId=123
For the repository itself, be sure to read up on query methods in the documentation: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods