2026.6.17笔记

1.创建分页配置类:

右键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;
    }
}

#2.创建Service(使用MyBatis-Plus的IService):

右键com.weitoutiao,创建service.NewsService类
```java
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的实现类

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 {
}

#3.测试分页

打开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());
    }
}

##4.逻辑删除不会在数据库中删除数据,只是通过一个字段用来标识被删除的记录,数据仍然保存在数据库中。

在实际的工作当中,因为数据非常重要,为了防止因用户误操作删除数据后无法恢复的问题,我们通常不会对数据做物理删除,即将数据从数据库中直接删除。而是多采用逻辑删除的方式,即不会真正在删除库删除数据,而是使用一个字段来标识它已经被删除。

如使用 isDeleted 字段标识该条记录是否已经被删除,0代表未删除,1代表已删除。此时对数据库做增删改查的SQL语句会发生如下变化:

• 插入:没有变化;

• 删除:转变为修改操作,即修改字段 isDeleted 为1;

• 修改:需要追加 where 子句,以排除 isDeleted 为1 的数据;

• 查询:需要追加 where 子句,以排除 isDeleted 为1 的数据。
posted @ 2026-06-18 22:23  一口小鑫  阅读(5)  评论(0)    收藏  举报