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、测试

相关推荐
Flying_Fish_roe10 分钟前
linux-安全管理-防火墙与网络安全
linux·数据库·oracle
A_cot22 分钟前
Redis 的三个并发问题及解决方案(面试题)
java·开发语言·数据库·redis·mybatis
2401_847056551 小时前
Altium Designer脚本工具定制
网络·数据库
神仙别闹1 小时前
基于Python+SQLite的课程管理系统
数据库·sqlite
掐指一算乀缺钱1 小时前
SpringBoot 数据库表结构文档生成
java·数据库·spring boot·后端·spring
少年负剑去2 小时前
django分发路由
数据库·django·sqlite
飞翔的佩奇2 小时前
xxl-job适配sqlite本地数据库及mysql数据库。可根据配置指定使用哪种数据库。
数据库·spring boot·mysql·sqlite·xxl-job·任务调度
吱吱鼠叔2 小时前
MATLAB数据文件读写:1.格式化读写文件
前端·数据库·matlab
小哇6662 小时前
spring-TransactionTemplate 编程式事务
数据库·spring
如意机反光镜裸3 小时前
CentOS7安装MySQL教程
数据库·mysql