程序员的资源宝库

网站首页 > gitee 正文

博客项目学习笔记三:基于MyBatisPlus实现分页功能

sanyeah 2024-04-03 18:36:32 gitee 7 ℃ 0 评论

博客项目目录: 请戳这里

准备

需求:我们需要把类似红框标记的文章,展示在首页,并且当文章数量大于一定数目时,进行分页展示

简单分析:每一篇文章包含了用户头像、用户id,用户名称,分类信息,文章标题,发表时间等等,这些信息分布在用户表、博客表和分类表里面,所以我们只需要联合三张表按一定条件进行查询,然后整合分页,就可以实现目标需求。

1.引入分页插件

在配置类添加获取PaginationInterceptor类方法,并且加上事务相关注解

@Configuration
@EnableTransactionManagement
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

}

2.定义查询结果

查询结果是文章以及其附带的一些信息整合分页后的页面信息

@Controller
public class IndexController extends BaseController{

    @RequestMapping({"", "/", "index"})
    public String index() {
    	//定义当前页初始值,以及每一页有多少项
        int pn = ServletRequestUtils.getIntParameter(req, "pn", 1);
        int size = ServletRequestUtils.getIntParameter(req, "size", 2);
        Page page = new Page(pn, size);
        // 1分页信息 2分类 3用户 4置顶  5精选 6排序
        IPage results = postService.paging(page, null, null, null, null, "created");
        req.setAttribute("pageData", results);
        req.setAttribute("currentCategoryId",0);
        return "index";
    }
}

postService提供了paging方法用于查询分页,但是只能返回Post信息,所以我们需要重写paging方法。
然后paging按“1分页信息 2分类 3用户 4置顶 5精选 6排序”这六个参数进行查询。

3.定义查询接口

public interface PostService extends IService<Post> {

    IPage paging(Page page, Long categoryId, Long userId, Integer level, Boolean recommend, String order);
}

4.在Service实现类进行具体实现

这里我们通过wrapper定义sql查询条件,然后利用postMapper结合sql表查询以及wrapper,page进行实际的查询。

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    PostMapper postMapper;

    @Override
    public IPage<PostVo> paging(Page page, Long categoryId, Long userId, Integer level, Boolean recommend, String order) {
        if(level == null) level = -1;

        QueryWrapper wrapper=new QueryWrapper<Post>()
                .eq(categoryId != null,  "category_id", categoryId)
                .eq(userId != null,  "user_id", userId)
                .eq(level == 0,  "level", 0)
                .gt(level > 0,  "level", 0)
                .orderByDesc(order != null, order);
        return postMapper.selectPosts(page,wrapper);
    }
}

返回的类型是一个整合了Post和用户以及分类的结合体,所以我们需要定义一个PostVo类:

@Data
public class PostVo extends Post {
    private Long authorId;
    private String authorName;
    private String authorAvatar;

    private String categoryName;
}

5.定义mapper查找接口

由于实际的查找是通过postMapper的selectPosts方法,所以我们要在mapper接口定义一个对应方法

@Component
public interface PostMapper extends BaseMapper<Post> {

    IPage<PostVo> selectPosts(Page page,@Param(Constants.WRAPPER) QueryWrapper wrapper);
}

QueryWrapper加上@Param注解,就可以把查询条件添加到sql里去

6.设计sql查询

在PostMapper.xml引入sql语句,查询文章信息,用户信息以及分类信息,${ew.customSqlSegment}可以引入QueryWrapper查询条件。

<select id="selectPosts" resultType="com.example.vo.PostVo">
        SELECT
            p.*,

            u.id AS authorId,
            u.username AS authorName,
            u.avatar AS authorAvatar,

            c.id AS categoryId,
            c.name AS categoryName
        FROM
            post p
                LEFT JOIN user u ON p.user_id = u.id
                LEFT JOIN category c ON p.category_id = c.id

            ${ew.customSqlSegment}

    </select>

7.测试

打断点进行测试,发现查找出来的results总共有7条记录,当前页是1,每一页有两条,符合设定。

再点开具体的记录,结果如下:

8.添加sql分析器插件(不建议生产使用)

依赖包:

<!-- sql分析器 -->
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.8.6</version>
        </dependency>

更改yml配置:

spring:
  datasource:
    #driver-class-name: com.mysql.cj.jdbc.Driver
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:mysql://localhost:3306/myblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: 429006huzhuo

resourse目录下添加spy.properties打印配置:

module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
deregisterdrivers=true
useprefix=true
excludecategories=info,debug,result,batch,resultset
dateformat=yyyy-MM-dd HH:mm:ss
#driverlist=org.h2.Driver
outagedetection=true
outagedetectioninterval=2

再次启动项目:

参考资料:

https://github.com/MarkerHub/eblog

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表