用mybatisplus写分页查询
时间: 2023-10-03 21:02:41 浏览: 35
1. 创建实体类和Mapper接口
首先,我们需要创建一个实体类,表示我们要查询的数据。假设我们要查询一个学生列表,那么我们可以创建一个名为Student的实体类:
```
public class Student {
private Long id;
private String name;
private Integer age;
private String gender;
// 其他属性省略
// getter和setter方法省略
}
```
接着,我们需要创建一个Mapper接口,用于定义查询方法:
```
public interface StudentMapper extends BaseMapper<Student> {
// 定义查询方法
}
```
2. 配置分页插件
MyBatis-Plus提供了一个分页插件,可以方便地实现分页查询。我们需要在配置文件中配置该插件:
```
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
```
3. 编写查询方法
在Mapper接口中,我们可以定义一个分页查询方法。假设我们要查询学生列表,并按照年龄从小到大排序,那么我们可以这样定义方法:
```
public interface StudentMapper extends BaseMapper<Student> {
List<Student> selectStudentPage(Page<Student> page, @Param("age") Integer age);
}
```
其中,Page<Student>表示分页信息,@Param("age")表示查询条件,这里我们只查询年龄等于指定值的学生。
4. 调用查询方法
最后,在Service层中调用查询方法即可:
```
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public Page<Student> getStudentList(Integer pageNum, Integer pageSize, Integer age) {
Page<Student> page = new Page<>(pageNum, pageSize);
studentMapper.selectStudentPage(page, age);
return page;
}
}
```
其中,pageNum和pageSize表示分页信息,age表示查询条件。
这样,我们就完成了用MyBatis-Plus实现分页查询的操作。