其他分享
首页 > 其他分享> > Mybatis分页详解

Mybatis分页详解

作者:互联网

思考:为什么分页?

使用Limit分页

select * from user limit 3;  #[0,n]

1.接口

    //分页
    List<User> getUserByLimit(Map<String,Integer> map);

2.Mapper.xml

    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

3.测试

    @Test
    public void getUserByLimit() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<String,Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userByLimit = mapper.getUserByLimit(map);
        for (User user : userByLimit) {
            System.out.println(user);
        }
        sqlSession.close();
    }

RowBounds分页

不再使用SQL实现分页

1.接口

//分页2
List<User> getUserByRowBounds();

2.mapper.xml

    <select id="getUserByRowBounds" parameterType="map" resultMap="UserMap">
        select * from mybatis.user
    </select>

3.测试

    @Test
    public void getUserByRowBounds() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
        //通过java代码层面实现分页
        List<User> userList = sqlSession.selectList("com.lu.dao.UserMapper.getUserByRowBounds",null,rowBounds);
        for (User user : userList
             ) {
            System.out.println(user);
        }
        sqlSession.close();
    }

分页插件

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

了解即可,万一以后公司的架构师,说要使用,你需要知道它是什么东西!

 

标签:map,分页,List,sqlSession,详解,user,Mybatis,RowBounds
来源: https://blog.csdn.net/ypxcan/article/details/114760739