spring boot +mybatis分页查询
这是spring boot集合mybatis的分页查询。
pom依赖:
<!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency>
往spring容器注入一个Bean,写在main方法下面就行,或者另外写个类,加上注解@Configuration,被spring boot容器扫描到就行:
@Bean public PageHelper pageHelper() { PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); p.setProperty("offsetAsPageNum", "true"); p.setProperty("rowBoundsWithCount", "true"); p.setProperty("reasonable", "true"); p.setProperty("dialect", "mysql"); p.setProperty("supportMethodsArguments", "false"); p.setProperty("pageSizeZero", "true"); pageHelper.setProperties(p); return pageHelper; }
创建一个抽象类,分页类需要继承这个抽象类AbstractPageForm。
import java.io.Serializable; import com.github.pagehelper.PageHelper; public abstract class AbstractPageForm<T extends AbstractPageForm<T>> implements Serializable { private static final long serialVersionUID = 1L; /** * @Description 页码为首页 */ protected int pageNum = 1; /** * @Description 每页显示数量,默认为10 */ protected int pageSize = 10; public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * @Title enablePaging * @Description 启用分页 * @return */ @SuppressWarnings("unchecked") public final T enablePaging() { PageHelper.startPage(pageNum, pageSize); return (T) this; } }
写一个分页类,继承上面个抽象类
import *.AbstractPageForm;//换成自己的包 public class TestPage extends AbstractPageForm<TestPage>{ /** * */ private static final long serialVersionUID = 1L; }
查询方法:
public PageInfo selectAll() { TestPage TestPage = new TestnPage(); List<Test> selectAll = TestMapper.selectAll(TestPage.enablePaging()); PageInfo<Test> pageInfo = new PageInfo<>(selectAll); return pageInfo; }