目录
接口说明
接口url:/tags/hot
请求方式:GET
请求参数:无
id
标签名称
我们期望点击标签关于文章的所有列表都显示出来
返回数据:
{
"success": true,
"code": 200,
"msg": "success",
"data": [
{
"id":1,
"tagName":"4444"
}
]
}
编码实现
Controller控制层
TagsController:
package com.huing.blog.controller;
import com.huing.blog.service.TagService;
import com.huing.blog.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author huing
* @create 2022-07-03 16:11
*/
@RestController
@RequestMapping("tags")
public class TagsController {
@Autowired
private TagService tagService;
@Value("${tag.hot.limit}")
private int limit;
/**
* 最热标签
* @return
*/
@GetMapping("hot")
public Result hot(){
return tagService.hots(limit);
}
}
在application.properties配置文件中添加:
# spring读取配置文件的数据:@Value("${tag.hot.limit}")
#取得tag最热标签个数
tag.hot.limit=6
Service业务逻辑层
TagService接口
/**
* 获取limit个最热标签
* @param limit
*/
Result hots(int limit);
TagServiceImpl实现类
@Override
public Result hots(int limit) {
/**
* 1.标签所拥的文章数量最多
* 2.根据tag_id分组计数,从大到小排列,取前limit
*/
List<Long> tagIds = tagMapper.findHotsTagIds(limit);
if (CollectionUtils.isEmpty(tagIds)){
return Result.success(Collections.emptyList());
}
//我们需要tagId和tagName
List<Tag> tagList = tagMapper.findTagsByTagIds(tagIds);
return Result.success(tagList);
}
Dao持久层
TagMapper:
/**
* 查询前limi个最热标签id
* @param limit
* @return
*/
List<Long> findHotsTagIds(int limit);
/**
* 根据标签id查询标签详情
* @param tagIds
* @return
*/
List<Tag> findTagsByTagIds(@Param("tagIds") List<Long> tagIds);
TagMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis配置文件-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.huing.blog.dao.mapper.TagMapper">
<!-- List<Tag> findTagsByArticleId(Long articleId);-->
<select id="findTagsByArticleId" parameterType="long" resultType="com.huing.blog.dao.pojo.Tag">
select id, avatar, tag_name as tagName
from ms_tag
where id in (
select tag_id
from ms_article_tag
where article_id = #{articleId}
)
</select>
<!--List<Long> findHotsTagIds(int limit);-->
<select id="findHotsTagIds" parameterType="int" resultType="java.lang.Long">
select tag_id
from ms_article_tag
group by tag_id
order by count(*) desc
limit #{limit}
</select>
<!-- List<Tag> findTagsByTagIds(List<Long> tagIds);-->
<select id="findTagsByTagIds" parameterType="list" resultType="com.huing.blog.dao.pojo.Tag">
select id,tag_name as tagName
from ms_tag
where id in
<foreach collection="tagIds" item="tagId" separator="," open="(" close=")">
#{tagId}
</foreach>
</select>
</mapper>
前端测试