Mongodb:业务应用(2)

需求:

1、获取保存到mongodb库中的搜索记录列表

2、实现删除搜索记录接口

保存搜索记录数据参考上篇Mongodb:业务应用(1)_Success___的博客-CSDN博客

获取记录列表

1、创建controller

复制代码
package com.heima.search.controller.v1;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.service.ArticleSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/history")
public class SearchHistoryController {
    
    @Autowired
    ArticleSearchService articleSearchService;

    @PostMapping("/load")
    public ResponseResult getHistory(){
        return articleSearchService.getHistory();
    }

}

2、service实现类

复制代码
    /**
     查询搜索历史
     @return
     */
    @Override
    public ResponseResult getHistory() {
        
        //查询当前用户下面的搜索记录
        Integer userId = AppThreadLocalUtil.getUser().getId();
        //构造条件
        Query query = Query.query(Criteria.where("userId").is(userId));
        //执行查询
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        //返回数据
        return ResponseResult.okResult(list);
    }

3、测试

返回成功

根据id删除搜索记录

1、实现controller

复制代码
    @PostMapping("/del")
    public ResponseResult delHistory(@RequestBody ApUserSearch userSearch){
        return articleSearchService.del(userSearch);
    }

2、service实现类

复制代码
    /*根据id删除搜索记录*/
    @Override
    public ResponseResult del(HistorySearchDto dto) {

        //检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //检查登录状态
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //执行删除
        mongoTemplate.remove(Query.query(Criteria.where("userId")
                .is(userId).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

3、测试

相关推荐
白云偷星子8 分钟前
MySQL笔记11
数据库·笔记·mysql
稚辉君.MCA_P8_Java1 小时前
WebSocket 是什么原理?为什么可以实现持久连接?
网络·数据库·websocket·网络协议
小光学长1 小时前
基于Vue的图书馆座位预约系统6emrqhc8(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
code小毛孩2 小时前
如何简单的并且又能大幅度降低任务队列的锁粒度、提高吞吐量?
java·jvm·数据库
风随心飞飞2 小时前
linux 环境下mysql 数据库自动备份和清库 通过crontab 创建定时任务实现mysql数据库备份
linux·数据库·mysql
奥尔特星云大使2 小时前
读写分离中间件简介
数据库·mysql·中间件·读写分离
友莘居士3 小时前
高效处理 Excel 海量数据入库:编程脚本、CSV 中间件、图形工具优化全攻略
数据库·中间件·excel·csv·海量数据·入库
Han.miracle4 小时前
数据库圣经第二章——简单的my.ini基础配置介绍
数据库
八怪4 小时前
KILL MTS的一个worker线程会怎么样
数据库
-Xie-5 小时前
Mysql杂志(三十一)——Join连接算法与子查询、排序优化
数据库·mysql