Mybatis中如何快速上手pagehelper分页插件

Mybatis05-Mybatis之分页插件pagehelper

​ 对于数据库的增删查改,Mybatis框架提供了sql映射文件配置,对于从数据库中查出的数据,如果我们想要分页展示,需要写两条sql语句,一条sql查询数据总数,一条sql进行分页,方案可行。如果借用第三方插件,效率更高,方便快捷,可乐而不为呢?

1.pagehelper地址:

开源中国介绍参考地址:http://www.oschina.net/p/mybatis_pagehelper

Github 源码介绍地址: https://github.com/pagehelper/Mybatis-PageHelper

2.环境搭建

为了方便,可以借用我上一篇博客Mybatis-Spring整合文章搭好的环境,但需要添加一些配置

1.pom.xml添加pagehelper依赖
<!--分页-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.11</version>
</dependency>
2.mybatis.xml全局配置文件,添加pagehelper插件
<?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>
    <settings>
        <!--
            数据库字段(带有_字符的字段) 自动转换为驼峰命名
        -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.mage.vo"/>
        <package name="com.mage.query"/>
    </typeAliases>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- config params as the following 参数配置我们使用默认,不需要配置,不影响使用-->
            <!--<property name="param1" value="value1"/>-->
        </plugin>
    </plugins>
</configuration>
3.代码实现
1.实体类
public class Account {
    private Integer id;
    private String aname;
    private String type;
    private BigDecimal money;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date createTime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date updateTime;
    private String remark;
    private  Integer userId;
    private User user;
public class AccountQuery {
    //默认展示第一页
    private Integer pageNum=1;
    //默认当前页展示记录的数量
    private Integer pageSize=10;
    private Integer userId;
    private String aname;
    private String type;
    private String time;
2.dao层接口AccountDao
public interface AccountDao {
   public List<Account> queryByParams(AccountQuery accountQuery);
}
3.AccountDao接口对应的sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=包名+接口名-->
<mapper namespace="com.mage.dao.AccountDao">
    <sql id="account_columns">
        id, aname, type, money, user_id, create_time, update_time, remark
    </sql>
    <!--动态sql02-where标签
        如果where后第一个过滤条件出现and/or mybatis自动忽略and/or 但不能其后省略连接的and/or-->
    <select id="queryByParams" parameterType="com.mage.query.AccountQuery" resultType="Account">
        select <include refid="account_columns"/> from account
        <where>
            <if test="null != userId">
                and user_id = #{userId}
            </if>
            <if test="null !=aname and aname !=''">
                and aname like concat('%',#{aname},'%')
            </if>
            <if test="null !=type and type !=''">
                and type = #{type}
            </if>
            <if test="null !=time and time !=''">
                and create_time >= #{time}
            </if>
        </where>
    </select>
</mapper>
4.Service层对应 AccountService类添加分页查询方法
@Service
public class AccountService {
    @Resource
    private AccountDao accountDao;
	//分页方式一:
    public List<Account> queryByParams(AccountQuery accountQuery){
        //PageHelper 类设置分页页号与每页大小
        PageHelper.startPage(accountQuery.getPageNum(),accountQuery.getPageSize());
        return accountDao.queryByParams(accountQuery);
    }
	//分页方式二:
    public PageInfo<Account> queryAccountByParamPageInfo(AccountQuery accountQuery){
        //PageHelper 类设置分页页号与每页大小
        PageHelper.startPage(accountQuery.getPageNum(),accountQuery.getPageSize());
        List<Account> accounts = accountDao.queryByParams(accountQuery);
        /*调用PageInfo中的构造器*/
        return new PageInfo<Account>(accounts,10);
    }
}
5.测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class TestApp{
    @Autowired
    private AccountService accountService;
    @Test
    public void test01(){
        //切换分页条件
        AccountQuery accountQuery = new AccountQuery();
        //设置当前页码
        accountQuery.setPageNum(1);
        //设置查询用户的id
        accountQuery.setUserId(100);
        //设置当前页面的展示用户记录数量
        accountQuery.setPageSize(6);
        accountService.queryByParams(accountQuery).forEach(a->{
            System.out.println(a);
        });
    }
    @Test
    public void test02(){
        AccountQuery accountQuery = new AccountQuery();
         //设置当前页码
        accountQuery.setPageNum(7);
        //设置查询用户的id
        accountQuery.setUserId(100);
        //设置当前页面的展示数量
        accountQuery.setPageSize(1);
        //查询的所有数据,都由PageInfo类进行分页展示
        PageInfo<Account> accountPageInfo = accountService.queryAccountByParamPageInfo(accountQuery);
        accountPageInfo.setNavigatePages(10);
        System.out.println("总记录:" + accountPageInfo.getTotal() + ":总页数:" + accountPageInfo.getPages() + ":导航页数:" + accountPageInfo.getNavigatePages());
        int[] navigatepageNums = accountPageInfo.getNavigatepageNums();
        for (int navigatepageNum : navigatepageNums) {
            System.out.println(navigatepageNum);
        }
        /*List<Account> list = accountPageInfo.getList();*/
        for (Account account : accountPageInfo.getList()) {
            System.out.println(account);
        }
    }
}

PageInfo类参数解释:

//当前页码
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//由于startRow和endRow不常用,这里说个具体的用法
//可以在页面中"显示startRow到endRow 共size条数据"
//当前页面第一个元素在数据库中的行号
private int startRow;
//当前页面最后一个元素在数据库中的行号
private int endRow;
//总记录数
private long total;
//总页数
private int pages;
//结果集
private List<T> list;
//前一页
private int prePage;
//下一页
private int nextPage;
//是否为第一页
private boolean isFirstPage = false;
//是否为最后一页
private boolean isLastPage = false;
//是否有前一页
private boolean hasPreviousPage = false;
//是否有下一页
private boolean hasNextPage = false;
//导航页码数
private int navigatePages;
//所有导航页号
private int[] navigatepageNums;
//导航条上的第一页
private int navigateFirstPage;
//导航条上的最后一页
private int navigateLastPage;

本片博客分享就到这,如果有什么小问题,希望你在评论区留言,如果本片博客对你有帮助的话,希望你能收藏,想要学习更多,就多多关注我,文章持续更新中,别忘了点赞哦!谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QZP51ZX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值