条件构造器 & 分页插件

一、教学目标
使用LambdaQueryWrapper构建查询条件。
配置MyBatis-Plus分页插件,实现新闻分页查询。
二、核心知识点(简要)
LambdaQueryWrapper:类型安全的查询条件构造器。
分页插件:自动拦截SQL添加LIMIT,并查询总记录数。
Page:分页参数对象。
三、操作步骤
创建分页配置类:
右键com.weitoutiao,创建config.MyBatisPlusConfig类
类中代码如下:

package com.weitoutiao.config;

import com.baomidou.mybatisplus.annotation.DbType;
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();
        // 创建分页插件并指定数据库类型(根据实际使用的数据库选择)
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 可选:超出最大页码时是否处理(false表示返回空数据,true表示返回最后一页)
        paginationInterceptor.setOverflow(false);
        // 将分页插件添加到拦截器容器[reference:0]
        interceptor.addInnerInterceptor(paginationInterceptor);
        return interceptor;
    }
}

创建Service(使用MyBatis-Plus的IService):
右键com.weitoutiao,创建service.NewsService类
NewsService中的代码如下:

package com.weitoutiao.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.weitoutiao.entity.News;

public interface NewsService extends IService<News> {
}
右键service,创建impl.NewsServiceImpl的实现类
NewsServiceImpl中的代码如下:
package com.weitoutiao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weitoutiao.entity.News;
import com.weitoutiao.mapper.NewsMapper;
import com.weitoutiao.service.NewsService;
import org.springframework.stereotype.Service;

@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
}

测试分页
打开test文件夹中的testSelect文件,在代码最后添加如下测试代码:

@SpringBootTest
class NewsServiceTest {
    @Autowired
    private NewsService newsService;
    @Test
    void testPage() {
        Page<News> page = new Page<>(1, 5);
        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(News::getPublishTime);
        Page<News> result = newsService.page(page, wrapper);
        System.out.println("总记录数:" + result.getTotal());
        System.out.println("当前页数据:" + result.getRecords());
    }
}

红色错误的代码,可以鼠标悬停到错误位置上,选择导入类即可解决
点击testPage旁边的运行按钮,进行测试
会报如下错误:
因为 MyBatis-Plus 开启了逻辑删除功能,但 news 表中没有 deleted 字段。
所以需要打开SQLyog, 在查询中执行如下语句
ALTER TABLE news ADD COLUMN deleted TINYINT DEFAULT 0 COMMENT '逻辑删除(0未删除,1已删除)';
在SQLyog中,先选中该条语句,再点击执行
点刷新,表中就会多一列deleted
回到IDEA中,再执行testPage的测试,还会报如下错误
需要在SQLyog中再执行如下语句:
ALTER TABLE news
ADD COLUMN update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间';
回到IDEA中,再执行testPage的测试,程序log已成功打印

posted on 2026-06-24 10:29  爱我的果果吖  阅读(10)  评论(0)    收藏  举报