MyBatis 分页插件--PageHelper

原来自己写分页,用sql语句limit实现,在mybatis的mapper xml上要写两个重复的sql,一个算count,一个得到具体的bean list。感觉好蠢。
多看别人代码的好处,就是能学习别人的经验。看到有人用PageHelper。这个能简化代码,而且只要一个sql 查询 bean list就可以。插件能帮你实现分页,和 count统计。
具体看下面代码。

xml中引入PageHelper

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.4</version>
        </dependency>

springboot注入PageHelper,这个要做,不然分页不生效

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * 分页初始化配置
 */
@Configuration
public class PageHelperConfig {
    /**
     * 注入pagehelper配置
     */
    @Bean
    public PageHelper getPageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("dialect", "mysql");
        //分页合理化
        properties.setProperty("reasonable", "false");
        //是否支持接口参数来传递分页参数,默认false
        properties.setProperty("supportMethodsArguments", "false");
        //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
        properties.setProperty("pageSizeZero", "true");
        //RowBounds参数offset作为PageNum使用 - 默认不使用
        properties.setProperty("offsetAsPageNum", "false");
        //RowBounds是否进行count查询 - 默认不查询
        properties.setProperty("rowBoundsWithCount", "false");
        properties.setProperty("returnPageInfo", "none");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

做数据的分页,在service中实现,page中包含一些 分页的信息,包括count

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.idss.controller.User;
import com.idss.dao.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestServiceImpl implements TestService{

    @Autowired
    private TestMapper testMapper;

    @Override
    public List<User> getUserByCondition(User user) {
        PageHelper.startPage(user.getPageNum(),user.getPageSize());
        List<User> list = testMapper.getUserByCondition();
        PageInfo<User> page = new PageInfo<User>(list);
        return page.getList();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值