springboot分页pagehelper+mybatis plus实现分页示例代码
时间: 2023-05-08 20:58:50 浏览: 280
PageHelper分页实例(带页面)
5星 · 资源好评率100%
Spring Boot是一个能够极大简化Spring应用开发的框架,而PageHelper是MyBatis的分页插件,而MyBatis Plus则是MyBatis的增强工具包。SpringBoot整合PageHelper和MyBatis Plus可以简化分页操作,示例代码如下:
1.首先,在pom.xml文件中添加PageHelper和MyBatis Plus的依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>最新版本号</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本号</version>
</dependency>
```
2.配置MyBatis Plus的分页插件
```java
@Configuration
public class MybatisPlusConfig {
@Autowired
private DataSource dataSource;
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
sqlSessionFactory.setPlugins(new Interceptor[]{paginationInterceptor()}); //添加分页插件
return sqlSessionFactory.getObject();
}
}
```
3.使用PageHelper的分页接口进行分页
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Page<User> findUserList(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.selectList(null);
PageInfo<User> pageInfo = new PageInfo<>(userList);
return pageInfo.toPageInfo();
}
}
```
4.使用MyBatis Plus的分页接口进行分页
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public IPage<User> findUserList(Integer pageNum, Integer pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
return userMapper.selectPage(page, null);
}
}
```
以上便是使用Spring Boot整合PageHelper和MyBatis Plus进行分页的示例代码。
阅读全文