springboot项目myBatis plus实现分页查询
时间: 2023-12-18 21:03:28 浏览: 95
1. 添加mybatis plus依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
```
2. 配置mybatis plus
在application.yml文件中添加以下配置:
```
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
global-config:
page-helper:
offset-as-page-num: true
limit-as-page-size: true
page-size-zero: true
page-size-max: 1000
```
- mapper-locations:指定mapper文件的位置
- configuration:mybatis的配置项,这里开启下划线转驼峰
- global-config:全局配置,其中page-helper是分页插件的配置
3. 编写mapper.xml文件
在mapper目录下新建一个xxxMapper.xml文件,例如UserMapper.xml,编写查询语句和分页语句,如下:
```
<select id="getUserList" parameterType="java.util.Map" resultMap="BaseResultMap">
select *
from user
where 1 = 1
<if test="name != null">
and name like concat('%', #{name}, '%')
</if>
order by create_time desc
</select>
<select id="getUserPage" parameterType="java.util.Map" resultMap="BaseResultMap">
select *
from user
where 1 = 1
<if test="name != null">
and name like concat('%', #{name}, '%')
</if>
order by create_time desc
limit #{startIndex}, #{pageSize}
</select>
```
其中getUserList是用于查询总记录数的语句,getUserPage是用于分页查询的语句。startIndex和pageSize是分页参数。
4. 编写service层
在service层中,注入UserMapper,并编写分页查询方法,如下:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Page<User> getUserPage(int pageNum, int pageSize, String name) {
Page<User> page = new Page<>(pageNum, pageSize);
Map<String, Object> params = new HashMap<>();
params.put("startIndex", (pageNum - 1) * pageSize);
params.put("pageSize", pageSize);
params.put("name", name);
List<User> userList = userMapper.getUserPage(params);
int total = userMapper.getUserList(params).size();
page.setRecords(userList);
page.setTotal(total);
return page;
}
}
```
Page是mybatis plus提供的分页对象,通过调用setRecords和setTotal方法,将查询结果和总记录数设置到Page对象中。
5. 编写controller层
在controller层中,注入UserService,并编写分页查询接口,如下:
```
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/page")
public Page<User> getUserPage(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam(required = false) String name) {
return userService.getUserPage(pageNum, pageSize, name);
}
}
```
通过调用getUserPage方法,返回分页查询结果。
至此,springboot项目myBatis plus实现分页查询就完成了。
阅读全文