美文网首页
吐槽模块以及文章模块集成spring-data-mongoDB

吐槽模块以及文章模块集成spring-data-mongoDB

作者: 神豪VS勇士赢 | 来源:发表于2019-03-10 18:15 被阅读0次
    image.png

    首先要创建模块 spit

    pom 里面引入 spring-data-mongoDB starter

    image.png

    创建 application.yml

    image.png

    创建启动类

    image.png

    pojo层如下:

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class Spit implements Serializable{
    @Id
    private String _id;
    private String content;
    private Date publishtime;
    private String userid;
    private String nickname;
    private Integer visits;
    private Integer thumbup;
    private Integer share;
    private Integer comment;
    private String state;
    private String parentid;
    }

    dao层

    public interface SpitDao extends MongoRepository<Spit, String> {
    /**
    * 根据上级id 查询吐槽列表 分页
    */
    public Page<Spit> findByParentid(String parentId, Pageable pageable);
    }

    service层

    @Service
    public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询全部记录
     *
     * @return List<Spit>
     */
    public List<Spit> findAll() {
        return spitDao.findAll();
    }
    
    /**
     * @param id
     * @return Spit
     */
    public Spit findById(String id) {
        return spitDao.findById(id).get();
    }
    
    /**
     * @param spit
     */
    public void add(Spit spit) {
        spit.set_id(idWorker.nextId() + "");
        spit.setPublishtime(new Date());
        spit.setVisits(0);
        spit.setShare(0);
        spit.setThumbup(0);
        spit.setComment(0);
        spit.setState("1");
        if (StringUtils.isNotEmpty(spit.getParentid())) {
            /**存在上级id 需要同时更新父级的信息*/
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment", 1);
            mongoTemplate.updateFirst(query, update, "spit");
        }
        spitDao.save(spit);
    }
    
    public void update(Spit spit) {
        spitDao.save(spit);
    }
    
    public void deleteById(String id) {
        spitDao.deleteById(id);
    }
    
    /**
     * @param parentid
     * @param page
     * @param size
     * @return Page<Spit>
     */
    public Page<Spit> findByParentid(String parentid, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        return spitDao.findByParentid(parentid, pageRequest);
    }
    
    /**
     * 吐槽点赞
     * 1)可以通过dao查询出来点赞数 之后加一操作
     * 2)使用mongoTemplete api 进行操作
     */
    public void updateThumbup(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, update, "spit");
    }
    

    }

    controller 层

    @RestController
    @RequestMapping(value = "/spit")
    @CrossOrigin
    public class SpitController {

    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 查询全部数据
     *
     * @return
     */
    @GetMapping
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", spitService.findAll());
    }
    
    /**
     * 根据ID查询
     *
     * @param spitId ID
     * @return
     */
    @GetMapping(value = "/{spitId}")
    public Result findById(@PathVariable String spitId) {
        return new Result(true, StatusCode.OK, "查询成功", spitService.findById(spitId));
    }
    
    /**
     * 增加
     *
     * @param spit
     */
    @PostMapping
    public Result add(@RequestBody Spit spit) {
    
        spitService.add(spit);
        return new Result(true, StatusCode.OK, "增加成功");
    }
    
    /**
     * 修改
     *
     * @param spit
     */
    @PutMapping(value = "/{spitId}")
    public Result update(@RequestBody Spit spit, @PathVariable String spitId) {
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true, StatusCode.OK, "修改成功");
    }
    
    /**
     * 删除
     *
     * @param spitId
     */
    @DeleteMapping(value = "/{spitId}")
    public Result deleteById(@PathVariable String spitId) {
        spitService.deleteById(spitId);
        return new Result(true, StatusCode.OK, "删除成功");
    }
    
    @GetMapping(value = "/comment/{parentid}/{page}/{size}")
    public Result findByParentId(@PathVariable String parentid, @PathVariable int page, @PathVariable int size) {
        Page<Spit> byParentid = spitService.findByParentid(parentid, page, size);
        return new Result(true, StatusCode.OK, "查询成功",
                new PageResult<Spit>(byParentid.getTotalElements(), byParentid.getContent()));
    }
    
    /**
     * 点赞
     * 这里面使用了redis 做了个校验  点赞的时候不能重复点赞
     */
    @PutMapping("/thumbup/{id}")
    public Result updateThumbup(@PathVariable String id) {
        /**判断用户是否点过赞 后期会用用户的id 不可能像下面一样写死的*/
        String userId = "20002";
        if (redisTemplate.opsForValue().get("thumbup_" + userId + "_" + id) != null) {
            return new Result(false, StatusCode.REMOTEERROR, "您已经点过赞了");
        }
        spitService.updateThumbup(id);
        redisTemplate.opsForValue().set("thumbup_" + userId + "_" + id, 1);
        return new Result(true, StatusCode.OK, "点赞成功");
    }
    /*增加文章的浏览量*/
    //TODO
    /*增加文章的分享数*/
    //TODO
    

    }

    吐槽部分点赞的代码是重构过来的 之前在点赞的时候是从 dao 层查出来数据 加一 在更新

    image.png
    image.png

    所以我们这里讲它重构了

    image.png

    同时需要注意的还有 我们在点赞的时候需要 注意不能重复点赞 我们在这里使用redis 来完成 引入redis依赖

    并加入配置

    image.png

    当我们发布吐槽的时候需要注意一点: 如果吐槽的parentid存在的话需要更新 parent 的回复数 +1

    image.png

    增加浏览量和分享数 大家自己完成吧

    文章模块完成评论功能

    集合如下所示:

    image.png

    在article 模块加入 mongoDB

    在配置文件中加入 mongo的配置

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class Comment implements Serializable{
    @Id
    private String _id;
    private String articleid;
    private String content;
    private String userid;
    private String parentid;
    private Date publishdate;
    }

    dao 层

    public interface CommentDao extends MongoRepository<Comment, String> {

    public List<Comment> findByArticleid(String articleid);
    

    }

    service层

    @Service
    @Transactional
    public class CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private ArticleDao articleDao;

    public void add(Comment comment) {
        comment.set_id(idWorker.nextId() + "");
        if (StringUtils.isNotEmpty(comment.getArticleid())) {
            articleDao.updateArticleComment(comment.getArticleid());
        }
        commentDao.save(comment);
    }
    
    public List<Comment> findByArticleid(String articleid) {
        return commentDao.findByArticleid(articleid);
    }
    

    }

    controller层

    @RequestMapping(value = "/comment")
    @RestController
    @CrossOrigin
    public class CommentController {

    @Autowired
    private CommentService commentService;
    
    @PostMapping
    public Result save(@RequestBody Comment comment) {
        commentService.add(comment);
        return new Result(true, StatusCode.OK, "提交成功");
    }
    
    @GetMapping("/article/{articleid}")
    public Result findByArticleId(@PathVariable String articleid) {
        return new Result(true, StatusCode.OK, "查询成功", commentService.findByArticleid(articleid));
    }
    /*删除评论自己完成*/
    

    }

    这里我们需要注意的是 当我们增加文章的回复的时候 我们要记得同步更新 Article 的回复数 +1

    相关文章

      网友评论

          本文标题:吐槽模块以及文章模块集成spring-data-mongoDB

          本文链接:https://www.haomeiwen.com/subject/bgkppqtx.html