『博客开发日记』之搜索相关接口实现

本文最后更新于 2026年3月13日 晚上

搜索接口


搜索接口需求

要有分页搜索功能

搜索出来

排序:置顶文章优先,然后按创建时间降序

只能搜索出已发布的文章

根据搜索关键字实现模糊查询匹配

代码实现

一下主要写服务层实现类如何写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 搜索接口服务实现类
*
* @author mengze
* @since 2026-03-08
*/
@Service("searchService")
public class SearchServiceImpl implements SearchService
{
@Autowired
private ArticleMapper articleMapper;

@Autowired
private CategoryService categoryService;

/**
* 搜索文章
*
* @param pageNum 页码
* @param pageSize 每页数量
* @param keyword 搜索关键词
* @return 搜索结果
*/
@Override
public ResponseResult search(Integer pageNum, Integer pageSize, String keyword) {
// 参数校验
if (StringUtils.isBlank(keyword)) {
return ResponseResult.okResult(new PageVo());
}

final String searchKeyword = keyword.trim();

// 构建查询条件
LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

// 只搜索已发布状态的文章
queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);

// 未删除的文章
queryWrapper.eq(Article::getDelFlag, SystemConstants.NOT_DELETED);

// 在标题和内容中进行模糊匹配
queryWrapper.and(wrapper ->
wrapper.like(Article::getTitle, searchKeyword)
.or()
.like(Article::getContent, searchKeyword)
);

// 排序:置顶文章优先,然后按创建时间降序
queryWrapper.orderByDesc(Article::getIsTop);
queryWrapper.orderByDesc(Article::getCreateTime);

// 分页查询
Page<Article> page = new Page<>(pageNum, pageSize);
Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);

// 获取查询结果
List<Article> articles = articlePage.getRecords();

// 填充分类名称
articles.forEach(article -> {
if (article.getCategoryId() != null) {
try {
article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
} catch (Exception e) {
// 如果分类不存在,设置为空字符串
article.setCategoryName("");
}
}
});

// 转换为VO对象(使用已经设置了categoryName的articles列表)
List<SearchArticleListVo> searchArticleListVos = BeanCopyUtils.copyBeanList(articles, SearchArticleListVo.class);

// 封装分页结果
PageVo pageVo = new PageVo(searchArticleListVos, articlePage.getTotal());

return ResponseResult.okResult(pageVo);
}
}

其中传给前端的Vo要有文章id,文章摘要,文章标题和文章内容


此博客系统的前台所包含的前端和后端基本开发完整(差一个文章所属标签和标签页未完善),因为先前已经写了一个分类是与标签功能相似的了, 而且后台系统中写文章相关也是要选择标签和分类的, 所以选择留到后续开发后台系统时再进行完善

PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2025 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记』之搜索相关接口实现
http://example.com/2026/03/13/『博客开发日记』之搜索相关接口实现/
作者
云梦泽
发布于
2026年3月13日
更新于
2026年3月13日
许可协议