阅读量:138
MyBatis Plus 实现分页功能非常简单,只需要使用 Page 类即可。下面是一个简单的示例:
- 首先在 Mapper 接口中定义一个查询方法,使用 Page 类作为参数:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
public interface UserMapper extends BaseMapper {
Page selectUserPage(Page page) ;
}
- 在 Mapper XML 文件中编写对应的 SQL 查询语句:
<select id="selectUserPage" resultType="User">
select * from user
</select>
- 在 Service 层中调用 Mapper 方法获取分页数据:
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public Page getUserPage(int pageNum, int pageSize) {
Page page = new Page<>(pageNum, pageSize);
return userMapper.selectUserPage(page);
}
}
- 最后在 Controller 层中调用 Service 方法获取分页数据并返回给前端:
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public Page getUsers(int pageNum, int pageSize) {
return userService.getUserPage(pageNum, pageSize);
}
}
这样就可以实现 MyBatis Plus 的分页功能。在调用 getUserPage 方法时,传入页码和每页数量即可获取相应的分页数据。