14. 实现业务功能--帖子列表

文章介绍了如何使用MyBatis进行论坛帖子列表的查询,包括按板块ID和首页的不同操作,以及与Service、Controller和前端界面的交互,涉及Mapper映射文件、DAO方法、Service接口和ControllerAPI的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 版块帖子列表

  • 对应版块中显示的帖子列表以发布时间降序排列(desc)
  • 不传入版块 Id 返回所有帖子

2. 实现逻辑

  1. 用户点击某个版块或首页时,将版块 Id 做为参数向服务器发送请求
  2. 服务器接收请求,并获取版块 Id,查询对应版块下的所有帖子
  3. 返回查询结果

如果 ID 为空,表示首页下的帖子列表,查询所有;

如果 ID 不为空,表示对应版块的帖子列表。

3. 参数要求

参数名描述类型默认值条件
boardId板块 IdLong可为空

4. 修改扩展 Mapper.xml

在 extension 目录下新建 ArticleExtMapper.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.ArticleMapper">
  <!--  定义表关系的结果集映射  -->
  <resultMap id="AllInfoResultMap" type="com.example.demo.model.Article" extends="ResultMapWithBLOBs">
    <!--    关联对象  -->
    <association property="user" resultMap="com.example.demo.dao.UserMapper.BaseResultMap" columnPrefix="u_"/>
  </resultMap>
  <!--  查询所有的帖子集合  -->
  <select id="selectAll" resultMap="AllInfoResultMap">
    select
    u.id as u_id,
    u.nickname as u_nickname,
    u.gender as u_gender,
    u.avatarUrl as u_avatarUrl,
    a.id,
    a.boardId,
    a.userId,
    a.title,
    a.visitCount,
    a.replyCount,
    a.likeCount,
    a.state,
    a.deleteState,
    a.createTime,
    a.updateTime
    from t_article as a ,t_user as u
    where a.userId = u.id
    and a.deleteState = 0
    order by a.createTime desc;
  </select>
</mapper>

5. 修改 DAO

在 dao 包下的 ArticleMapper 中添加方法声明:
/**
     * 主⻚中显⽰的帖⼦列表以发布时间降序排列
     * 查询所有的帖子集合
     * @return 帖⼦列表
     */
    List<Article> selectAll ();

6. 创建 Service 接口

在 services 包下新建 IArticleService 接口:

public interface IArticleService {
    /**
     * 主⻚中显⽰的帖⼦列表以发布时间降序排列
     * 查询所有的帖子集合
     * @return 帖⼦列表
     */
    List<Article> selectAll ();
}

7. 实现 Service 接口

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    
    @Resource
    ArticleMapper articleMapper;
    
    @Override
    public List<Article> selectAll() {
        // 调用 DAO
        List<Article> result = articleMapper.selectAll();
        // 返回结果
        return result;
    }
}

8. 生成测试方法

@SpringBootTest
class ArticleServiceImplTest {

    @Resource
    private IArticleService articleService;
    @Resource
    private ObjectMapper objectMapper;
            
    @Test
    void selectAll() throws JsonProcessingException {
        List<Article> articles = articleService.selectAll();
        System.out.println(objectMapper.writeValueAsString(articles));
    }
}

9. 实现 Controller

在 ArticleController 中提供对外的 API 接口:

@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @ApiOperation("获取板块帖⼦列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(){
        // 调用 Service
        List<Article> articles = articleService.selectAll();
        // 判断是否为空
        if(articles == null){
            articles = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(articles);
    }
}

10. API 访问测试

11. 实现前端界面

// ========================= 获取帖子列表 =======================
    // 成功后,调用listBuildArticleList()方法,构建帖子列表
    $.ajax({
      type: 'GET',
      url: 'article/getAllByBoardId' + queryString,
      // 成功回调
      success: function(respData){
        if(respData.code == 0){
          // 成功
          listBuildArticleList(respData.data);
        }else{
          // 失败
          $.toast({
              heading : '警告',
              text : respData.message,
              icon : 'Warning'
            }); 
          }
        },
        // 失败回调
        error: function(){
          $.toast({
              heading : '错误',
              text : '出错了,请联系管理员',
              icon : 'error'
            });
        }

    });

12. 获取版块信息

12.1 修改扩展 Mapper.xml
  <!--  查询所有的帖子集合  -->
  <select id="selectByBoardId" resultMap="AllInfoResultMap">
    select
    u.id as u_id,
    u.nickname as u_nickname,
    u.gender as u_gender,
    u.avatarUrl as u_avatarUrl,
    a.id,
    a.boardId,
    a.userId,
    a.title,
    a.visitCount,
    a.replyCount,
    a.likeCount,
    a.state,
    a.deleteState,
    a.createTime,
    a.updateTime
    from t_article as a ,t_user as u
    where a.userId = u.id
    and a.deleteState = 0
    and a.boardId = #{boardId,jdbcType=BIGINT}
    order by a.createTime desc;
  </select>
12.2 修改 DAO
/**
     * 根据板块ID 查询帖子列表
     * @param boardId 板块Id
     * @return List<Article>
     */
    List<Article> selectByBoardId (Long boardId);
12.3 创建 Service 接口
    /**
     * 根据板块ID 查询帖子列表
     * @param boardId 板块Id
     * @return List<Article>
     */
    List<Article> selectByBoardId (Long boardId);
12.4 实现 Service 接口
@Override
    public List<Article> selectByBoardId(Long boardId) {
        // 非空校验
        if(boardId == null || boardId <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用 DAO
        List<Article> result = articleMapper.selectByBoardId(boardId);
        return result;
    }
12.5 测试
    @Test
    void selectByBoardId() throws JsonProcessingException {
        List<Article> articles = articleService.selectByBoardId(1l);
        System.out.println(objectMapper.writeValueAsString(articles));
        
        articles = articleService.selectByBoardId(2l);
        System.out.println(objectMapper.writeValueAsString(articles));
        
        articles = articleService.selectByBoardId(20l);
        System.out.println(objectMapper.writeValueAsString(articles));
    }

测试结果如下:

12.6 实现 Controller
@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @ApiOperation("获取板块帖⼦列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId((@ApiParam(value = "版块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        // 声明返回的集合
        List<Article> articles;
        // 根据传入的 boardId 来获取不同的集合
        if(boardId == null){
            // 首页,查询所有
            articles = articleService.selectAll();
        }else {
            // 查询对应的板块的帖子集合
            articles = articleService.selectByBoardId(boardId);
        }
        // 判断是否为空
        if(articles == null){
            articles = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(articles);
    }
}
12.7 测试结果

13. 获取指定板块列表

客户端发送请求传入版块Id,服务器响应对应板块的详情。

参数名

描述

类型默认值条件
id版块 Idlong必要
13.1 创建 Service 接口
    /**
     * 根据 ID 查询板块信息
     * @param id 版块Id
     * @return Board
     */
    Board selectById (Long id);
13.2 实现 Service 接口
    @Override
    public Board selectById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用 DAO
        Board board = boardMapper.selectByPrimaryKey(id);
        return null;
    }
13.3 测试
    @Test
    void selectById() throws JsonProcessingException {
        Board board = boradService.selectById(1l);
        System.out.println(objectMapper.writeValueAsString(board));

        board = boradService.selectById(2l);
        System.out.println(objectMapper.writeValueAsString(board));

        board = boradService.selectById(20l);
        System.out.println(objectMapper.writeValueAsString(board));
    }

测试结果:

13.4 实现 Controller
    @ApiOperation("获取版块详情")
    @GetMapping("/getById")
    public AppResult<Board> getBoardInfo(@Param("版块Id") @RequestParam("id") @NonNull Long id){
        // 调用 Service
        Board board = boradService.selectById(id);
        // 返回结果
        return AppResult.success(board);
    }
13.5 实现前端界面
    // ========================= 获取版块信息 =======================
    // 
    function getBoardInfo (boardId) {
      if (!boardId) {
        return;
      }
      // 发送请求, 成功后,显示版块相关信息
      $.ajax({
        type: 'GET',
        url: 'board/getById?id=' + boardId,
        // 成功回调
        success: function(respData){
          if(respData.code == 0){
            // 成功
            let board = respData.data;
            // 1. 设置版块名
            $('#article_list_board_title').html(board.name);
            // 2. 设置版块下的贴子数
            $('#article_list_count_board').html('帖子数量:' + board.articleCount);
            // 3. 是否显示帖子标签
            $('#article_list_count_board').show();
          }else{
            // 失败
            $.toast({
                heading : '警告',
                text : respData.message,
                icon : 'Warning'
              }); 
            }
          },
          // 失败回调
          error: function(){
            $.toast({
                heading : '错误',
                text : '出错了,请联系管理员',
                icon : 'error'
              });
          }
      });
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值