使用mybatis plus的@Select自定义sql时,如何实现通用的分页查询?

在 MyBatis Plus 中使用 @Select 自定义 SQL 实现通用的分页查询,可按以下步骤操作:

1. 配置分页插件

首先,需要在项目中配置 MyBatis Plus 的分页插件。以 Spring Boot 项目为例,在配置类中添加分页插件的 Bean:

java 复制代码
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

2. 定义实体类

假设我们有一个 User 实体类:

java 复制代码
import com.baomidou.mybatisplus.annotation.TableName;

@TableName("user")
public class User {
    private Long id;
    private String name;
    private Integer age;

    // 构造函数、Getter 和 Setter 方法
    public User() {}

    public User(Long id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3. 定义 Mapper 接口

在 Mapper 接口中使用 @Select 注解编写自定义 SQL,并接收 Page 对象作为参数:

java 复制代码
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Select;

public interface UserMapper extends BaseMapper<User> {

    @Select("SELECT * FROM user WHERE age > #{age}")
    IPage<User> selectUserByAge(Page<User> page, Integer age);
}

4. 实现分页查询服务

在服务层调用 Mapper 接口的方法进行分页查询:

java 复制代码
import com.baomidou.mybatisplus.core.metadata.IPage;
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 IPage<User> getUserByAgePage(Integer pageNum, Integer pageSize, Integer age) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return userMapper.selectUserByAge(page, age);
    }
}

5. 调用分页查询方法

在控制器或测试类中调用服务层的方法进行分页查询:

java 复制代码
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public IPage<User> getUsers(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam Integer age) {
        return userService.getUserByAgePage(pageNum, pageSize, age);
    }
}

解释

  • 分页插件配置 :MybatisPlusInterceptor 是 MyBatis Plus 的拦截器,PaginationInnerInterceptor 是分页拦截器,用于实现分页功能。
  • Mapper 接口 :@Select 注解中的 SQL 是自定义的查询语句,Page 对象作为参数传入,MyBatis Plus 会自动处理分页逻辑。
  • 服务层 :创建 Page 对象,设置当前页码和每页记录数,调用 Mapper 接口的方法进行分页查询。
  • 控制器:接收前端传入的页码、每页记录数和查询条件,调用服务层的方法进行分页查询并返回结果。

通过以上步骤,就可以在 MyBatis Plus 中使用 @Select 自定义 SQL 实现通用的分页查询。

相关推荐
for_ever_love__19 分钟前
Redis 数据类型全景:五种基础类型怎么用、什么时候用
数据库·redis·数据类型·hash·使用场景·zset·排行榜
SmartSoftHelp开发辅助优化19 分钟前
SmartSoftHelp DeepCore XSuite Pro Global Eco AIAgent 2026.V29 专业国际版
数据库·oracle
honsor34 分钟前
以太网温湿度传感器:RJ45直连机房的环境监控新方案
运维·网络·数据库·物联网·安全·云计算·github
西索斯coding34 分钟前
Kimi k2.7-code-highspeed 接入 Cline 教程:baseURL 路由变更 + model_id 正确写法
java·服务器·数据库·ai
浪子明X1 小时前
MongoDB 迁移方案评审:用双写窗口和回放样本控制切换风险
数据库·mongodb
stark张宇1 小时前
InnoDB锁机制全景图:全局锁、表锁、行锁、意向锁到底怎么用?
数据库·后端
坊钰1 小时前
【LangChain框架入门级】10. 文本向量与向量数据库(Embedding / Redis / Pinecone / MMR)
数据库·python·langchain·embedding
2601_960356381 小时前
2027零售商品计划岗能力拆解:统计学、SQL、Excel与业务指标怎么结合
sql·excel·零售
Omics Pro1 小时前
研究证实AI虚拟细胞可用于药物靶点发现
数据库·人工智能·算法·机器学习·自然语言处理
好奇的菜鸟1 小时前
GORM 入门(二):从 database/sql 平滑过渡到 GORM
数据库·sql