分页(Limit+RowBounds+插件)

为什么分页?

  减少数据的处理量

1.使用Limit分页

  语法:select *from user limit startIndex,pageSize;
  startIndex:起始位置(0开始), pageSize:记录条数

StuMapper.java

public interface StuMapper {
  List<Student> selectByLimit(Map<String,Integer> map);
}

StuMapper.xml
这里因为表里字段和数据库字段不匹配,用了结果集映射。

   <resultMap id="getSno" type="stu">
        <result property="sno" column="sn"/>
    </resultMap>
    <!--分页 -->
    <select id="selectByLimit" resultMap="getSno" parameterType="map">
        select  * from test.stu limit #{startIndex},#{pageSize}
    </select>

StuService.java
这是service层

  @Override
    public List<Student> selectByLimit(Map<String,Integer> map) {
        return stuMapper.selectByLimit(map);

  工具类

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resources="mybatis-config.xml";
            InputStream inputStream= Resources.getResourceAsStream(resources);
            sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}

  测试类


@Test
    public void LimitTest(){
        SqlSession session=MybatisUtils.getSession();
    StuMapper mapper = session.getMapper(StuMapper.class);
    HashMap<String,Integer>map=new HashMap<String,Integer>();
    map.put("startIndex",0);
    map.put("pageSize",2);
    List<Student> list = mapper.selectByLimit(map);
    for (Student student : list) {
        System.out.println(student);

    }


    session.close();
}

2.RowBounds

StuMapper.java

public interface StuMapper {
    List<Student> selectByRowBounds();
}

StuMapper.xml
resultMap是因为字段不匹配,可在上文中查找

   <select id="selectByRowBounds" resultMap="getSno">
        select  * from test.stu
    </select>

测试类:

    @Test
    public void getUserByRowBounds(){

        SqlSession sqlSession = MybatisUtils.getSession();

 RowBounds rowBounds=new RowBounds(0,2);
        //通过java代码层面实现分页
        List<Student> list = sqlSession.selectList("com.my.mapper.StuMapper.selectByRowBounds",null,rowBounds);
        for (Student student : list) {
            System.out.println(student);
        }



        sqlSession.close();

    }

结果
在这里插入图片描述

3.Mybatis分页插件PageHelper

      学习地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值