How does MyBatis achieve pagination?
MyBatis enables pagination queries through the RowBounds object.
Firstly, define a method in the Mapper interface that takes in a RowBounds object and other query parameters as parameters. The method should return a List object.
List<User> getUsersByPage(RowBounds rowBounds, @Param("param1") String param1, @Param("param2") String param2);
Next, write the corresponding SQL statement in the Mapper’s XML file, using the LIMIT keyword to implement pagination. The LIMIT keyword is used to limit the number of rows in the query results, with the first parameter being the offset of the query results and the second parameter being the number of records per page.
<select id="getUsersByPage" resultType="User">
SELECT * FROM users
WHERE param1 = #{param1} AND param2 = #{param2}
LIMIT #{offset}, #{limit}
</select>
To implement pagination in the Java code, simply call the method of the Mapper interface with the RowBounds object and other query parameters.
int pageNum = 1; // 当前页码
int pageSize = 10; // 每页记录数
int offset = (pageNum - 1) * pageSize; // 计算偏移量
RowBounds rowBounds = new RowBounds(offset, pageSize);
List<User> users = userMapper.getUsersByPage(rowBounds, param1, param2);
In the above code, pageNum represents the current page number, pageSize represents the number of records per page, and offset represents the offset of the query results. With this information, we can calculate the parameters of the RowBounds object. Then, we call the method of the Mapper interface to conduct a paginated query and obtain the paginated result, users.