Springboot/Thymeleaf-如何根据URL执行不同的SQL查询



我希望能够根据之前选择的类别显示不同的数据。例如,我目前有一些类别,一旦单击,就会将用户重定向到一个新页面,该页面将显示该类别的所有相关信息。url应该类似于localhost:8080/category/321,其中该类别的ID是最后一个。我需要找到一种方法来执行不同的sql查询,具体取决于所选的URL/类别。例如,如果选择了类别1,我希望所有类别ID为1的评论都使用这样的语句显示

SELECT * FROM Comments WHERE CategoryID='the category id of the category that was selected';

我在应用程序的其他地方使用了findAll((方法来显示所有数据,但我不确定如何根据URL执行特定的查询。我还简要介绍了findByID()谢谢

您可以在存储库中添加其他方法。对于您的情况,类似于:

List<Comment> findByCategoryID(Long categoryId);

Spring将使用方法名称解析查询。

或者使用jpql:

@Query("SELECT c FROM Comment AS c WHERE c.CategoryID = :categoryId")
List<Request> findByCategoryID(Long categoryId);

或者使用与Example一起使用的findAll重载。Java文档-在这里。

示例:

Comment comment = new Comment;
comment.setCategoryId(1);
List<Comment> comments = repository.findAll(Example.of(comment));

您需要区分控制器和存储库。控制器负责与HTTP和HTML相关的一切,因此解析URL、生成HTML等。存储库是负责查询数据库的类。

控制器通常如下所示:

@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";
}
}

第二种方法将处理形式为/comments/123的URL。

在您的示例中,如果注释有一个类别,那么很可能会使用查询参数,而不是路径变量。在这种情况下,您的控制器方法将是:

@GetMapping
public String commentsByCategory(@QueryParameter("categoryId")Long categoryId, Model model) {
List<Comments> comments = repository.findAllByCategoryId(categoryId);
model.addAttribute("comments", comments);
return "comments-by-category";
}

那么URL将是/comments?categoryId=123

对于存储库本身,请务必阅读文档中的查询方法:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-方法

最新更新