Mybatis分页的实现 及PageHelper的使用

目录

一.分页的原理

二.Mybatis实现

三.PageHelper

第⼀步:引⼊依赖

第⼆步:在mybatis-config.xml⽂件中配置插件

第三步:编写Java代码


一.分页的原理

pageindex 页数 pagindex 页内数据

(pageindex-1)*pagesize,pagesize

SELECT * FROM table 
LIMIT(PageNo - 1)*PageSize, PageSize;

二.Mybatis实现

测试程序 就全查出来 然后分页
        int pageIndex = 1;
        pageIndex = (pageIndex - 1) * pageSize;
        List<Employee> employees = mapper.queryEmployeeByPage(pageIndex, pageSize);
  List<Employee> queryEmployeeByPage(@Param("pageindex") int pageindex, @Param("pagesize")int pageSize);
  

三.PageHelper

第⼀步:引⼊依赖

pom.xml

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.3.3</version>
</dependency>

第⼆步:在mybatis-config.xml⽂件中配置插件

typeAliases标签下⾯进⾏配置:

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

第三步:编写Java代码

关键点:PageHelper.startPage(pageIndex,pageSize); //开启分页

  PageInfo<Car> pageInfo = new PageInfo<>(cars, 5); 获取分页信息

  • 在查询语句之前开启分⻚功能。

  • 在查询语句之后封装PageInfo对象。(PageInfo对象将来会存储到request域当中。在⻚⾯上展 示。)

 //开启分页

        int pageNum=2;
        int pageSize=4;
        PageHelper.startPage(pageNum,pageSize);
        // 执⾏查询语句
        List<Car> cars = mapper.queryCarList();
        cars.forEach(new Consumer<Car>() {
            @Override
            public void accept(Car car) {
                System.out.println(car);
            }
        });

        // 获取分⻚信息对象
        PageInfo<Car> pageInfo = new PageInfo<>(cars, 5);

        System.out.println(pageInfo);

四关于sqlSession 线程代码

public class SqlSessionUtil {
  static   ThreadLocal<SqlSession> sqlSessionThreadLocal = new InheritableThreadLocal<>();

    static SqlSession sqlSession;

    static {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory build = sqlSessionFactoryBuilder.build(inputStream);
            sqlSession = build.openSession(false);
            sqlSessionThreadLocal.set(sqlSession);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSession;
    }

    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
        sqlSessionThreadLocal.remove();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值