springboot整合mybatis-plus分页查询
时间: 2023-09-05 08:07:46 浏览: 132
1. 添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2. 配置文件
在application.yml文件中添加以下配置:
```yml
mybatis-plus:
# mapper.xml文件的位置
mapper-locations: classpath:/mapper/*.xml
# 实体类所在的包名
typeAliasesPackage: com.example.entity
```
3. 实体类
```java
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
```
4. Mapper接口
```java
public interface UserMapper extends BaseMapper<User> {
List<User> selectPage(Page<User> page, @Param("name") String name);
}
```
5. Service层
```java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public IPage<User> selectPage(Page<User> page, String name) {
return baseMapper.selectPage(page, name);
}
}
```
6. Controller层
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public IPage<User> selectPage(Page<User> page, String name) {
return userService.selectPage(page, name);
}
}
```
7. 测试
启动应用,访问 http://localhost:8080/user/list?page=1&size=2&name=Tommy 进行测试。
其中,page为页码,size为每页大小,name为查询条件。
返回结果如下:
```
{
"records": [
{
"id": 1,
"name": "Tommy",
"age": 28,
"email": "tommy@example.com"
},
{
"id": 2,
"name": "Tommy",
"age": 25,
"email": "tommy@example.com"
}
],
"total": 3,
"size": 2,
"current": 1,
"pages": 2
}
```
其中,records为查询结果列表,total为总记录数,size为每页大小,current为当前页码,pages为总页数。
阅读全文