编写一个springboot+mybatis分页功能
时间: 2023-12-31 11:16:21 浏览: 109
好的,以下是一个简单的示例:
1. 首先,需要在pom.xml文件中添加相关依赖:
```xml
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL Connector Java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
```
2. 配置数据源和MyBatis:
```properties
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# MyBatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
```
3. 创建实体类和Mapper接口:
```java
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
@Mapper
public interface UserMapper {
List<User> selectAll();
}
```
4. 创建Mapper XML文件:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectAll" resultMap="BaseResultMap">
SELECT * FROM user
</select>
</mapper>
```
5. 创建分页查询的Service和Controller:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public PageInfo<User> findAll(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.selectAll();
return new PageInfo<>(userList);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public PageInfo<User> findAll(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
return userService.findAll(pageNum, pageSize);
}
}
```
6. 启动应用程序并测试分页查询接口。访问 http://localhost:8080/user/list 即可查看分页查询结果。
以上就是一个简单的Spring Boot + MyBatis分页查询的示例。
阅读全文