mybatis-plus分页
- 定义一个 Mapper 接口,继承
BaseMapper
,用于操作数据库:
javaCopy codeimport com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
- 在你的 Service 类中,注入上面定义的 Mapper,并实现分页查询方法:
javaCopy codeimport com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public Page<User> getUsersByPage(int pageNum, int pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Page<User> resultPage = userMapper.selectPage(page, queryWrapper);
return resultPage;
}
}
- 在你的 Controller 中,调用 Service 的分页查询方法并返回结果:
javaCopy codeimport 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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/page")
public Page<User> getUsersByPage(
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "5") int pageSize) {
return userService.getUsersByPage(pageNum, pageSize);
}
评论区