用mybatis-plus写一个分页查询
时间: 2024-05-11 19:14:32 浏览: 111
Mybatis框架(分页查询)
假设我们有一个实体类User,它有id、name和age三个属性,使用mybatis-plus进行分页查询的代码如下:
1. 定义mapper接口
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
IPage<User> selectUserPage(Page<User> page, @Param("name") String name, @Param("age") Integer age);
}
```
2. 编写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.mapper.UserMapper">
<select id="selectUserPage" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="name != null and name != ''">
AND name like concat('%', #{name}, '%')
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
</mapper>
```
3. 在Service中调用mapper接口的方法
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public IPage<User> selectUserPage(Page<User> page, String name, Integer age) {
return userMapper.selectUserPage(page, name, age);
}
}
```
4. 在Controller中调用Service的方法,获取分页数据
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/page")
public IPage<User> selectUserPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize,
String name, Integer age) {
// 构建分页对象
Page<User> page = new Page<>(pageNum, pageSize);
// 调用Service的方法,获取分页数据
return userService.selectUserPage(page, name, age);
}
}
```
以上就是使用mybatis-plus进行分页查询的完整代码示例。
阅读全文