目 录CONTENT

文章目录

mybatis-plus分页

不争
2024-01-02 / 0 评论 / 0 点赞 / 16 阅读 / 4033 字

mybatis-plus分页

  1. 定义一个 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> {
}
  1. 在你的 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;
    }
}
  1. 在你的 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);
    }

image-20230822215240156

0

评论区