springboot整合mybatis实现分页
时间: 2024-09-16 16:03:16 浏览: 71
Spring Boot整合MyBatis实现分页通常涉及以下几个步骤:
1. **引入依赖**:在`pom.xml`文件中添加MyBatis和分页插件的依赖,如`mybatis-spring-boot-starter`和`pagehelper`。
```xml
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
</dependencies>
```
2. **配置MyBatis**:在`application.properties`或`application.yml`中设置数据源和其他MyBatis配置,包括SqlSessionFactoryBean。
```properties
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
mybatis.mapperLocations=classpath:mapper/*.xml
mybatis.config-location=classpath:mybatis-config.xml
```
3. **创建Mapper接口**:定义包含分页查询方法的Mapper接口,例如:
```java
import org.apache.ibatis.annotations.*;
public interface UserMapper {
@Select("SELECT * FROM user LIMIT #{offset}, #{limit}")
List<User> list(@Param("offset") int offset, @Param("limit") int limit);
}
```
4. **启用分页插件**:在`mybatis-config.xml`中启用PageHelper,并配置相关属性(如页面大小、SQL方言等)。
```xml
<configuration>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
<!-- 其他可选配置 -->
</plugin>
</plugins>
</configuration>
```
5. **在服务层调用分页查询**:通过@Autowired注入UserMapper并使用其提供的方法获取分页结果。
```java
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public PageResult<User> getUsers(int pageNum, int pageSize) {
return userMapper.list(pageNum, pageSize); // 使用PageResult接收分页结果
}
}
// 分页对象(如PageResult)
public class PageResult<T> extends Wrapper<T[]> implements Pageable {
// 实现相关接口的方法
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)