当前位置:   article > 正文

Spring Boot利用Spring Data JPA实现排序与分页查询实战(附源码,超详细)_如何使用spring boot实现分页和排序

如何使用spring boot实现分页和排序

在实际开发场景中,排序与分页查询是必须的,幸运的是Spring Data JPA充分考虑了排序与分页查询的场景,为我们提供Sort类 Page接口 Pageable接口 下面通过一个实战来阐明

1:创建持久化实体类

创建名为com.ch.ch6_4.entity的包 并在该包中创建名为Article和Author的持久化实体类

代码如下

Article

  1. package com.ch.ch6_2.entity;
  2. import java.io.Serializable;
  3. import javax.persistence.Basic;
  4. import javax.persistence.CascadeType;
  5. import javax.persistence.Column;
  6. import javax.persistence.Entity;
  7. import javax.persistence.FetchType;
  8. import javax.persistence.GeneratedValue;
  9. import javax.persistence.GenerationType;
  10. import javax.persistence.Id;
  11. import javax.persistence.JoinColumn;
  12. import javax.persistence.Lob;
  13. import javax.persistence.ManyToOne;
  14. import javax.persistence.Table;
  15. import javax.validation.constraints.NotEmpty;
  16. import javax.validation.constraints.Size;
  17. import com.fasterxml.jackson.annotation.JsonIgnore;
  18. import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  19. @Entity
  20. @Table(name = "article_table")
  21. @JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
  22. public class Article implements Serializable{
  23. private static final long serialVersionUID = 1L;
  24. @Id
  25. @GeneratedValue(strategy = GenerationType.IDENTITY)
  26. private int id;
  27. //标题
  28. @NotEmpty(message = "标题不能为空")
  29. @Size(min = 2, max = 50)
  30. @Column(nullable = false, length = 50)
  31. private String title;
  32. //文章内容
  33. @Lob //大对象,映射 为MySQL的Long文本类型
  34. @Basic(fetch = FetchType.LAZY)
  35. @NotEmpty(message = "内容不能为空")
  36. @Size(min = 2)
  37. @Column(nullable = false)
  38. private String content;
  39. //所属作者,文章与作者是多对一的关系
  40. @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=false)
  41. //可选属性optional=false,表示author不能为空。删除文章,不影响用户
  42. @JoinColumn(name="id_author_id")//设置在article表中的关联字段(外键)
  43. @JsonIgnore
  44. private Author author;
  45. public int getId() {
  46. return id;
  47. }
  48. public void setId(int id) {
  49. this.id = id;
  50. }
  51. public String getTitle() {
  52. return title;
  53. }
  54. public void setTitle(String title) {
  55. this.title = title;
  56. }
  57. public String getContent() {
  58. return content;
  59. }
  60. public void setContent(String content) {
  61. this.content = content;
  62. }
  63. public Author getAuthor() {
  64. return author;
  65. }
  66. public void setAuthor(Author author) {
  67. this.author = author;
  68. }
  69. }

Author

  1. package com.ch.ch6_2.entity;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. import javax.persistence.CascadeType;
  5. import javax.persistence.Entity;
  6. import javax.persistence.FetchType;
  7. import javax.persistence.GeneratedValue;
  8. import javax.persistence.GenerationType;
  9. import javax.persistence.Id;
  10. import javax.persistence.OneToMany;
  11. import javax.persistence.Table;
  12. import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  13. @Entity
  14. @Table(name = "author_table")
  15. @JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
  16. public class Author implements Serializable{
  17. private static final long serialVersionUID = 1L;
  18. @Id
  19. @GeneratedValue(strategy = GenerationType.IDENTITY)
  20. private int id;
  21. //作者名
  22. private String aname;
  23. //文章列表,作者与文章是一对多的关系
  24. @OneToMany(
  25. mappedBy = "author",
  26. cascade=CascadeType.ALL,
  27. targetEntity = Article.class,
  28. fetch=FetchType.LAZY
  29. )
  30. private List<Article> articleList;
  31. public int getId() {
  32. return id;
  33. }
  34. public void setId(int id) {
  35. this.id = id;
  36. }
  37. public String getAname() {
  38. return aname;
  39. }
  40. public void setAname(String aname) {
  41. this.aname = aname;
  42. }
  43. public List<Article> getArticleList() {
  44. return articleList;
  45. }
  46. public void setArticleList(List<Article> articleList) {
  47. this.articleList = articleList;
  48. }
  49. }

2:创建数据访问层

创建名为com.ch.ch6_4repository的包 并在该包中创建名为AuthorRepository的接口

  1. package com.ch.ch6_2.repository;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.data.jpa.repository.Query;
  4. import com.ch.ch6_2.entity.Author;
  5. public interface AuthorRepository extends JpaRepository<Author, Integer>{
  6. /**
  7. * 根据文章标题包含的内容,查询作者(关联查询)
  8. * 相当于JPQL语句:select a from Author a inner join a.articleList t where t.title like %?1%
  9. */
  10. public Author findByArticleList_titleContaining(String title);
  11. /**
  12. * 根据文章标题包含的内容,查询作者(关联查询)
  13. */
  14. @Query("select a from Author a inner join a.articleList t where t.title like %?1%" )
  15. public Author findAuthorByArticleListtitleContaining(String title);
  16. }

3:创建业务层

 创建名为com.ch.ch6_4.service的包 并在该包中创建名为ArticleAndAuthorService的接口和接口实现类ArticleAndAuthorServiceImpl

接口

  1. package com.ch.ch6_2.service;
  2. import java.util.List;
  3. import com.ch.ch6_2.entity.Article;
  4. import com.ch.ch6_2.entity.Author;
  5. public interface AuthorAndArticleService {
  6. public void saveAll();
  7. public List<Article> findByAuthor_id(Integer id);
  8. public List<Article> findByAuthor_aname(String aname);
  9. public Author findByArticleList_titleContaining(String title);
  10. public Author findAuthorByArticleListtitleContaining(String title);
  11. }

接口实现类

  1. package com.ch.ch6_2.service;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import com.ch.ch6_2.entity.Article;
  7. import com.ch.ch6_2.entity.Author;
  8. import com.ch.ch6_2.repository.ArticleRepository;
  9. import com.ch.ch6_2.repository.AuthorRepository;
  10. @Service
  11. public class AuthorAndArticleServiceImpl implements AuthorAndArticleService{
  12. @Autowired
  13. private AuthorRepository authorRepository;
  14. @Autowired
  15. private ArticleRepository articleRepository;
  16. @Override
  17. public void saveAll() {
  18. //保存作者(先保存一的一端)
  19. Author a1 = new Author();
  20. a1.setAname("陈恒1");
  21. Author a2 = new Author();
  22. a2.setAname("陈恒2");
  23. ArrayList<Author> allAuthor = new ArrayList<Author>();
  24. allAuthor.add(a1);
  25. allAuthor.add(a2);
  26. authorRepository.saveAll(allAuthor);
  27. //保存文章
  28. Article at1 = new Article();
  29. at1.setTitle("JPA的一对多111");
  30. at1.setContent("其实一对多映射关系很常见111。");
  31. //设置关系
  32. at1.setAuthor(a1);
  33. Article at2 = new Article();
  34. at2.setTitle("JPA的一对多222");
  35. at2.setContent("其实一对多映射关系很常见222。");
  36. //设置关系
  37. at2.setAuthor(a1);//文章2与文章1作者相同
  38. Article at3 = new Article();
  39. at3.setTitle("JPA的一对多333");
  40. at3.setContent("其实一对多映射关系很常见333。");
  41. //设置关系
  42. at3.setAuthor(a2);
  43. Article at4 = new Article();
  44. at4.setTitle("JPA的一对多444");
  45. at4.setContent("其实一对多映射关系很常见444。");
  46. //设置关系
  47. at4.setAuthor(a2);//文章3与文章4作者相同
  48. ArrayList<Article> allAt = new ArrayList<Article>();
  49. allAt.add(at1);
  50. allAt.add(at2);
  51. allAt.add(at3);
  52. allAt.add(at4);
  53. a
  54. public Author findByArticleList_titleContaining(String title) {
  55. return authorRepository.findByArticleList_titleContaining(title);
  56. }
  57. @Override
  58. public Author findAuthorByArticleListtitleContaining(String title) {
  59. return authorRepository.findAuthorByArticleListtitleContaining(title);
  60. }
  61. }

4:创建控制器类

创建名为com.ch,ch6_4.controller的包 并在该包中创建名为TestSortAndPage的控制器类

  1. package com.ch.ch6_4.controller;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import com.ch.ch6_4.entity.Author;
  9. import com.ch.ch6_4.service.ArticleAndAuthorService;
  10. @Controller
  11. public class TestSortAndPage {
  12. @Autowired
  13. private ArticleAndAuthorService articleAndAuthorService;
  14. @RequestMapping("/findByAnameContaining")
  15. @ResponseBody
  16. public List<Author> findByAnameContaining(String aname, String sortColum){
  17. return articleAndAuthorService.findByAnameContaining(aname, sortColum);
  18. }
  19. @RequestMapping("/findAllAuthorByPage")
  20. /**
  21. * @param page第几页
  22. */
  23. public String findAllAuthorByPage(Integer page, Model model){
  24. return articleAndAuthorService.findAllAuthorByPage(page, model);
  25. }
  26. }

5:创建View视图页面

创建index.html页面 部分代码如下

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>显示分页查询结果</title>
  6. <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
  7. <link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
  8. </head>
  9. <body>
  10. <div class="panel panel-primary">
  11. <div class="panel-heading">
  12. <h3 class="panel-title">Spring Data JPA分页查询</h3>
  13. </div>
  14. </tr>
  15. <tr>
  16. <td colspan="2" align="right">
  17. <ul class="pagination">
  18. <li><a><span th:text="${page}"></span></a></li>
  19. <li><a><span th:text="${totalPage}"></span></a></li>
  20. <li><a><span th:text="${totalCount}"></span></a></li>
  21. <li>
  22. <a th:href="@{findAllAuthorByPage(page=${page-1})}" th:if="${page != 1}">上一页</a>
  23. </li>
  24. <li><a th:href="@{findAllAuthorByPage(page=${page+1})}" th:if="${page != totalPage}">下一页</a>
  25. </li>
  26. </ul>
  27. </td>
  28. </tr>
  29. </tbody>
  30. </table>
  31. </div>
  32. </div>
  33. </div>
  34. </div>
  35. </body>
  36. </html>

6:运行主类  效果如下

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/769182
推荐阅读
相关标签
  

闽ICP备14008679号