1.用SQL语句
例如 : 其中 offset = 2, limit =5 表示 查询的数据 是从第二行开始 总共查5条
LIMIT 关键字指定查询结果的数据条数,使用 OFFSET 关键字指定查询结果的起始行。
SELECT * FROM 表名 LIMIT #{OFFSET},#{pageSize}
有时可能会是 SELECT * FROM 表名 LIMIT #{pageSize},#{LIMIT}
select * from t_student limit 2,5
1.在mapper.xml中写法
<select id ="selectStudentList" ,parameterType ="StudentBo",resultType="StudentVO">
select * from t_student
where 1=1
<if test=" pageSize !=null and pageSize >= 0">
limit #{pageSize}, #{Limit}
</if>
</select>
2.Service层中 调用mapper 接口定义的方法 并传入分页查询的参数
int pageSize = 100
int pageNum =1
int offset =(pageNum -1) *pageSize
public interface studentService { List<StudentVo> selectStudentList(StudentBo studentBo) }
2.Mybatis使用分页插件
1.首先要在pom.xml文件中添加Mybatis分页插件
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.1</version>
</dependency>
2.在mybatis的配置文件中配置分页插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="" value="mysql"/>
</plugin>
</plugins>
3. 在mapper.xml中写法
<select id ="xxx",resultType="xxxx">
select *from t_student
</select>
4.在service层中调用mapper接口定义的方法
int pageSize = 10;
int pageNum = 1;PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.selectAllUsers();
3.RowBounds
1.mapper文件中
public interface StudentMapper {
List<Student> selectByPage(RowBounds rowBounds);
}
2.在xml的映射文件中
<select id="selectByPage" resultType="Student">
SELECT * FROM student
</select>
3.service层中
// 使用RowBounds进行分页查询
int offset = (pageNum - 1) * pageSize; // pageNum是当前页码,pageSize是每页显示条数
int limit = pageSize;
RowBounds rowBounds = new RowBounds(offset, limit);
List<Student> studentList= studentMapper .selectByPage(rowBounds);
PS:RowBounds是将所有符合条件的数据全都查询到内存中,然后在内存中对数据进行分页
如我们查询student表中id>0的数据,然后分页查询sql如下:
select * from student where id >0 limit 5,10
但使用RowBounds后,会将id>0的所有数据都加载到内存中,然后跳过offset=5条数据,截取10条数据出来,若id>0的数据有100万,则100w数据都会被加载到内存中,从而造成内存泄露 不建议使用这个类 仅是个人建议