MyBatis Limit and RowBounds realize paging


〇、Preparation

database:

create database MyBatis_DB;
use MyBatis_DB;
create table user(
	id int primary key auto_increment,
	name varchar(32) not null,
	pwd varchar(32) not null
);

Insert picture description here
Then just insert a few pieces of data

Next, create a Mavenproject, injection MySql, MyBatis, Junit, LOG4Jdependence

Create a table Userentity class, create an UserMapperinterface, UserMapper.xmland test class
Insert picture description here
Next, start to implement paging query

One, Limit realizes paging

The first step is to write the UserMapperinterface

List<User> findUserByLimit(Map<String,Integer> map);

The second step is to write a UserMapper.xmlfile and write sql, where the receiving parameter is one Map:

    <select id="findUserByLimit" resultType="User" parameterType="map">
        select * from mybatis_db.user limit #{startPage},#{Page}
    </select>

The third step is to write a test class. First, make a Mapstorage parameter to be transmitted, then call the method, output the result, and finally close the connection

    //获取SqlSession
    private SqlSession sqlSession = MyBatisUtils.getSqlSession();
    //获取mapper
    private UserMapper mapper = sqlSession.getMapper(UserMapper.class);   
    //limit分页
    @Test
    public void findUserByLimitTest(){
    
    
        Map<String,Integer> map = new HashMap<String, Integer>();
        map.put("startPage",0);
        map.put("Page",5);
        List<User> userByLimit = mapper.findUserByLimit(map);
        for (User user : userByLimit) {
    
    
            System.out.println(user);
        }
        sqlSession.close();
    }

Output result:
Insert picture description here

Two, RowBounds realizes paging | not recommended

The first step is to write the interface

List<User> findUserByRowBounds();

The second step, writing XML:

    <select id="findUserByRowBounds" resultType="User">
        select * from mybatis_db.user;
    </select>

The third step is to write the test class

    //获取SqlSession
    private SqlSession sqlSession = MyBatisUtils.getSqlSession();
    //RowBounds实现分页
    @Test
    public void findUserByRowBoundsTest(){
    
    
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(0, 5);
        List<User> UserList = sqlSession.selectList(
                "com.wzq.mapper.UserMapper.findUserByRowBounds",
                null, rowBounds);
        for (User user : UserList) {
    
    
            System.out.println(user);
        }
        sqlSession.close();
    }

test:
Insert picture description here

Guess you like

Origin blog.csdn.net/lesileqin/article/details/113053053