spring boot整合mybatis-plus和pagehelper分页插件,附项目源码
时间: 2023-08-09 21:00:54 浏览: 180
springBoot+mybatis集成插件pageHelper
spring boot整合mybatis-plus和pagehelper分页插件是一种常见的开发方式,可以实现数据库的分页查询功能。下面是一个简单示例项目的源码,以供参考:
首先,需要在pom.xml文件中添加相关依赖:
```xml
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!-- PageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
</dependencies>
```
在application.properties(或application.yml)文件中配置数据库连接信息:
```yaml
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.configuration.map-underscore-to-camel-case=true
```
创建一个简单的实体类User:
```java
public class User {
private Long id;
private String username;
private String password;
// 省略getter和setter方法
}
```
创建一个Mapper接口UserMapper:
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 省略其他方法
List<User> getUsersByPage(Page<User> page, @Param("username") String username);
}
```
创建一个Service接口UserService以及其实现类UserServiceImpl:
```java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public IPage<User> getUsersByPage(Page<User> page, String username) {
return userMapper.getUsersByPage(page, username);
}
}
```
在Controller中注入UserService,并进行分页查询操作:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public IPage<User> getUsers(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
@RequestParam(value = "size", defaultValue = "10") Integer pageSize,
@RequestParam(value = "username", required = false) String username) {
Page<User> page = new Page<>(pageNum, pageSize);
return userService.getUsersByPage(page, username);
}
}
```
至此,就完成了spring boot整合mybatis-plus和pagehelper分页插件的配置和使用。
请注意,这是一个简单示例项目,实际使用中可能需要根据需求进行适当调整和修改。
阅读全文