PageHelper.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /**
  2. * Copyright (c) 2011-2020, hubin (jobob@qq.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. * <p>
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.baomidou.mybatisplus.plugins.pagination;
  17. import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
  18. /**
  19. * <p>
  20. * 分页辅助类
  21. * </p>
  22. *
  23. * @author liutao , hubin
  24. * @since 2017-06-24
  25. */
  26. public class PageHelper {
  27. // 分页本地线程变量
  28. private static final ThreadLocal<Pagination> LOCAL_PAGE = new ThreadLocal<>();
  29. /**
  30. * <p>
  31. * 获取总条数
  32. * </p>
  33. */
  34. public static int getTotal() {
  35. if (isPageable()) {
  36. return LOCAL_PAGE.get().getTotal();
  37. } else {
  38. throw new MybatisPlusException("The current thread does not start paging. Please call before PageHelper.startPage");
  39. }
  40. }
  41. /**
  42. * <p>
  43. * 释放资源并获取总条数
  44. * </p>
  45. */
  46. public static int freeTotal() {
  47. int total = getTotal();
  48. remove();// 释放资源
  49. return total;
  50. }
  51. /**
  52. * <p>
  53. * 获取分页
  54. * </p>
  55. */
  56. public static Pagination getPagination() {
  57. return LOCAL_PAGE.get();
  58. }
  59. /**
  60. * <p>
  61. * 设置分页
  62. * </p>
  63. */
  64. public static void setPagination(Pagination page) {
  65. LOCAL_PAGE.set(page);
  66. }
  67. /**
  68. * <p>
  69. * 启动分页
  70. * </p>
  71. *
  72. * @param current 当前页
  73. * @param size 页大小
  74. */
  75. public static void startPage(int current, int size) {
  76. LOCAL_PAGE.set(new Pagination(current, size));
  77. }
  78. /**
  79. * <p>
  80. * 是否存在分页
  81. * </p>
  82. *
  83. * @return
  84. */
  85. public static boolean isPageable() {
  86. return LOCAL_PAGE.get() != null;
  87. }
  88. /**
  89. * <p>
  90. * 释放资源
  91. * </p>
  92. */
  93. public static void remove() {
  94. LOCAL_PAGE.remove();
  95. }
  96. }