需求:
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 {@AutowiredArticleSearchService articleSearchService;@PostMapping("/load")public ResponseResult getHistory(){return articleSearchService.getHistory();}}
2、service实现类
/**查询搜索历史@return*/@Overridepublic 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删除搜索记录*/@Overridepublic 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、测试