mybatis plus 分页的简单案例
时间: 2023-06-08 14:08:12 浏览: 105
mybatis-plus分页查询的实现示例
可以参考以下代码:
```
//1.引入相关包和类
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
//2.定义一个service接口
public interface UserService extends IService<User> {
//分页查询用户信息
public IPage<User> selectUserPage(Page<User> page, QueryWrapper<User> queryWrapper);
}
//3.实现service接口,具体实现分页查询
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public IPage<User> selectUserPage(Page<User> page, QueryWrapper<User> queryWrapper) {
return baseMapper.selectPage(page, queryWrapper);
}
}
//4.在controller中调用分页查询的方法
@Controller
@RequestMapping("/test")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public String users(Model model) {
//当前页数和每页记录数
Page<User> page = new Page<>(1, 10);
//查询条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age", 20);//年龄大于20的记录
//调用分页查询的方法
IPage<User> userList = userService.selectUserPage(page, queryWrapper);
//将查询结果返回到页面
model.addAttribute("userList", userList.getRecords());
model.addAttribute("total", userList.getTotal());
model.addAttribute("current", userList.getCurrent());
model.addAttribute("size", userList.getSize());
return "user_list";
}
}
//5.在html页面中展示分页数据
<table>
<thead>
<tr>
<td>名称</td>
<td>年龄</td>
<td>性别</td>
</tr>
</thead>
<tbody>
<tr th:each="user : ${userList}">
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td th:text="${user.gender}"></td>
</tr>
</tbody>
</table>
<nav>
<ul class="pagination">
<li class="page-item"><a class="page-link" th:href="@{'/test/users?page=' + ${current-1}}">Previous</a></li>
<li class="page-item"><a class="page-link" th:href="@{'/test/users?page=' + 1}">1</a></li>
<li class="page-item"><a class="page-link" th:href="@{'/test/users?page=' + 2}">2</a></li>
<li class="page-item"><a class="page-link" th:href="@{'/test/users?page=' + 3}">3</a></li>
<li class="page-item"><a class="page-link" th:href="@{'/test/users?page=' + ${current+1}}">Next</a></li>
</ul>
</nav>
```
以上代码基于Mybatis-Plus和Spring Boot框架实现了一个简单的分页查询。在UserService中定义了selectUserPage方法,实现了分页查询的具体逻辑;而在UserController中调用了该方法,并将查询结果返回给页面,同时在html页面中展示了分页数据。
阅读全文