Mongodb:业务应用(2)

文章讲述了如何在SpringBoot应用中,通过Controller和Service实现从MongoDB数据库获取搜索记录列表及根据ID删除搜索记录的功能。包括了Controller层的定义、Service层的查询和删除操作以及测试部分的结果展示。
摘要由CSDN通过智能技术生成

需求:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值