springboot和mybatis实现分页查询
时间: 2023-11-30 14:41:22 浏览: 119
以下是SpringBoot和MyBatis实现分页查询的步骤:
1.在pom.xml文件中引入MyBatis和PageHelper的依赖包:
```xml
<!-- 引入MyBatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 引入MyBatis 分页插件pageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
```
2.在application.properties文件中配置PageHelper:
```properties
# PageHelper配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
```
3.在Mapper.xml文件中编写分页查询的SQL语句:
```xml
<!-- 分页查询 -->
<select id="selectByPage" resultType="com.example.demo.entity.User">
select * from user
<where>
<if test="name != null and name != ''">
and name like concat('%', #{name}, '%')
</if>
</where>
order by id desc
</select>
```
4.在Service层中调用Mapper的分页查询方法:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> selectByPage(Integer pageNum, Integer pageSize, String name) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.selectByPage(name);
return new PageInfo<>(userList);
}
}
```
5.在Controller层中接收前端传来的分页参数,并调用Service层的分页查询方法:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public PageInfo<User> selectByPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize,
String name) {
return userService.selectByPage(pageNum, pageSize, name);
}
}
```
阅读全文