MyBatis realizes data paging operation

Data paging

Why do you need paging?

When learning persistence layer frameworks such as mybatis, we will often add, delete, modify, and query data. The most used is to query the database. When querying a large amount of data, we often use paging to query, that is, small processing each time. Part of the data, so that the pressure on the database is within the controllable range.

limit realizes paging

#语法
SELECT * FROM table LIMIT stratIndex,pageSize

SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15  

#为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:   
SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.  

#如果只给定一个参数,它表示返回最大的记录行数目:   
SELECT * FROM table LIMIT 5; //检索前 5 个记录行  

#换句话说,LIMIT n 等价于 LIMIT 0,n。 

step:

1. Modify the Mapper file

<select id="selectUser" parameterType="map" resultType="user">
  select * from user limit #{startIndex},#{pageSize}
</select>

2. Mapper interface, the parameter is map

//选择全部用户实现分页
List<User> selectUser(Map<String,Integer> map);

3. Pass in the parameter test in the test class

Inference: starting position = (current page-1) * page size

//分页查询 , 两个参数startIndex , pageSize
@Test
public void testSelectUser() {
    
    
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   int currentPage = 1;  //第几页
   int pageSize = 2;  //每页显示几个
   Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("startIndex",(currentPage-1)*pageSize);
   map.put("pageSize",pageSize);

   List<User> users = mapper.selectUser(map);

   for (User user: users){
    
    
       System.out.println(user);
  }

   session.close();
}

RowBounds pagination

In addition to using Limit to implement paging at the SQL level, we can also use RowBounds to implement paging at the Java code level. Of course, this method can be used as an understanding. Let's see how to achieve it!

step:

1. Mapper interface

//选择全部用户RowBounds实现分页
List<User> getUserByRowBounds();

2. Mapper file

<select id="getUserByRowBounds" resultType="user">
select * from user
</select>

3. Testing

Here, we need to use the RowBounds class

@Test
public void testUserByRowBounds() {
    
    
   SqlSession session = MybatisUtils.getSession();

   int currentPage = 2;  //第几页
   int pageSize = 2;  //每页显示几个
   RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize);

   //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了]
   List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserByRowBounds", null, rowBounds);

   for (User user: users){
    
    
       System.out.println(user);
  }
   session.close();
}

Guess you like

Origin blog.csdn.net/david2000999/article/details/115141957