【mybatis】mybaits分页插件的使用

1.引入pom依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>
<dependency>
    <groupId>com.github.miemiedev</groupId>
    <artifactId>mybatis-paginator</artifactId>
    <version>1.2.15</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>3.2.1</version>
</dependency>

2. 在Mybatis配置xml中配置拦截器插件:

【mybatis】mybaits分页插件的使用

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
		PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 配置分页插件 -->
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->        
        	<property name="dialect" value="mysql"/>
		</plugin>
	</plugins>
</configuration>

3.定义返回结果类

/**
 * @author evan_qb
 * @date 2018/10/16
 * 定义分页参数
 */
public class PageResult {
    private long total;

    private List<?> rows;

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<?> getRows() {
        return rows;
    }

    public void setRows(List<?> rows) {
        this.rows = rows;
    }
}

4.接着在service层中查询数据

public PageResult getItemList(int page, int rows) {
    TbItemExample example = new TbItemExample();
    //分页处理
    PageHelper.startPage(page,rows);
    List<TbItem> itemList = itemMapper.selectByExample(example);
    //创建一个返回值对象
    PageResult result = new PageResult();
    result.setRows(itemList);
    //获取总记录数
    PageInfo<TbItem> pageInfo = new PageInfo<>(itemList);
    result.setTotal(pageInfo.getTotal());

    return result;
}

5.Controller类接收page,rows参数,并将结果以json格式返回

@RequestMapping("list")
@ResponseBody
public PageResult itemList(Integer page, Integer rows){
    PageResult result = itemService.getItemList(page, rows);
    return result;
}

【mybatis】mybaits分页插件的使用