美文网首页@IT·互联网
SpringBoot集成Mongodb

SpringBoot集成Mongodb

作者: GG_lyf | 来源:发表于2020-09-09 20:02 被阅读0次

    前言

      在学了用MongoDB之后,总感觉直接操作那个客户端比较痛苦。咱是程序员啊,咱能干的就是将自己的想法以代码的形式展示出来。用Navicat连接MongoDB,那么就开始上java代码,毕竟SpringBoot不是白学的啊!!!!


    开搞

      1.创建完一个空的maven项目之后就开始导包了(springboot的MongoDB)。

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    

      2.在src/main/resource下创建一个application.yml

    server:
      port: 9006  #端口自定义
    spring:
      application:
        name: tensquare-spit     #项目的名称,可写可不写
      data:
        mongodb:
          host: localhost     #mongodb所在的那个主机,最好写成localhost或127.0.0.1或固定的IP,我在换了无线网之后报了个超时的错,还找了半天,看着配置都没错,就IP错了
          port: 27017            #开放的端口
          database: spitdb        #数据库名
    

      3.创建实体类(包括get,set和toString)

    import org.springframework.data.annotation.Id;
    
    import java.io.Serializable;
    import java.util.Date;
    public class Spit implements Serializable {
      @Id //和_id相对应,自动映射为_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;
    
      //空参有参,get,set和toSring
        ....
    }
    

      4.创建Dao,从而操作数据库

    import com.tensquare.spit.pojo.Spit;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    public interface SpitDao extends MongoRepository<Spit,String> {
    
      public Page<Spit> findByParentid(String parentid, Pageable pageable);
    
    }
    

      5.创建service层,用于操作 Dao

    import com.tensquare.spit.dao.SpitDao;
    import com.tensquare.spit.pojo.Spit;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.core.query.Update;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Service;
    import util.IdWorker;
    
    import java.util.Date;
    import java.util.List;
    
    @Service
    public class SpitService {
    
      @Autowired
      private SpitDao spitDao;//注入的Dao
    
      @Autowired
      private IdWorker idWorker;//用于动态生成id
    
      @Autowired
      private MongoTemplate mongoTemplate;//使用的Mongo的模板,在springboot整合mongodb的时候只用到了简单的逻辑,有些复杂的逻辑倒是需要自己用自带的模板写
    
    //查找所有
      public List<Spit> findAll(){
        return spitDao.findAll();
      }
    //通过id查询
      public Spit findById(String id){
        return spitDao.findById(id).get();
      }
    //保存一个
      public void save(Spit spit){
        spit.set_id(String.valueOf(idWorker.nextId()));
        spit.setPublishtime(new Date());//发布日期
        spit.setVisits(0);//浏览量         
        spit.setShare(0);//分享数         
        spit.setThumbup(0);//点赞数         
        spit.setComment(0);//回复数         
        spit.setState("1");//状态
        System.out.println("parentid:"+spit.getParentid());
        spitDao.save(spit);
        //如果当前添加的吐槽有父节点,那么父节点的吐槽数+1
        if (spit.getParentid() != null && !"".equals(spit.getParentid())){
          Query query = new Query();
          query.addCriteria(Criteria.where("_id").is(spit.get_id()));
          Update update = new Update();
          update.inc("comment",1);
          mongoTemplate.updateFirst(query,update,"spit");
          System.out.println("comment:"+spit.getComment());
        }
        System.out.println(spit);
      }
    //更新一个
      public void update(Spit spit){
         spitDao.save(spit);
      }
    //通过id删除一个
      public void deleteById(String id){
        spitDao.deleteById(id);
      }
    //分页
      public Page<Spit> findPage(int page,int size){
        PageRequest of = PageRequest.of(page-1, size);
        return spitDao.findAll(of);
      }
    //通过某些条件分页
      public Page<Spit> findByParentid(String parentid, int page,int size){
        PageRequest of = PageRequest.of(page-1, size);
        return spitDao.findByParentid(parentid,of);
      }
    //通过id更新一条数据的字段
      public void thumbupById(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");
      }
    }
    

      6.创建controller,用以和service进行交互

    import com.tensquare.spit.pojo.Spit;
    import com.tensquare.spit.service.SpitService;
    import entity.PageResult;
    import entity.Result;
    import entity.StatusCode;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.web.PageableDefault;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController //两个注解的合体
    @CrossOrigin //用于跨域
    @RequestMapping("/spit")
    public class SpitController {
    
      @Autowired
      private SpitService spitService;
      @Autowired
      private RedisTemplate redisTemplate;
    
      @GetMapping("findAll")
      public Result findAll() {
        return new Result(true, StatusCode.OK, "查找成功", spitService.findAll());
      }
    
      @GetMapping("findById/{id}")
      public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查找成功", spitService.findById(id));
      }
    
      @PostMapping("saveOne")
      public Result save(@RequestBody Spit spit) {
        spitService.save(spit);
        return new Result(true, StatusCode.OK, "添加成功");
      }
    
      @PutMapping("updateOne")
      public Result update(@RequestBody Spit spit) {
        spitService.update(spit);
        return new Result(true, StatusCode.OK, "修改成功");
      }
    
    
      @DeleteMapping("deleteById/{id}")
      public Result deleteById(@PathVariable String id) {
        spitService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
      }
    
      @GetMapping("findPage/{page}/{size}")
      public Result findPage(@PageableDefault(sort = {"id"}, direction = Sort.Direction.DESC) @PathVariable int page, @PathVariable int size) {
        Page<Spit> page1 = spitService.findPage(page, size);
        return new Result(true, StatusCode.OK, "查找成功", new PageResult<>(page1.getTotalElements(), page1.getContent()));
      }
    
    
      @GetMapping("findByParentid/{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<>(byParentid.getTotalElements(), byParentid.getContent()));
      }
    
      @PutMapping("thumbup/{spitid}")
      public Result thumbupById(@PathVariable String spitid) {
        //判断当前是否已经点赞,还没做认证,暂时把user写死
        String userid = "111111";
        if (redisTemplate.opsForValue().get("thumbup_" + userid) != null) {
          return new Result(true, StatusCode.REPERROR, "不能重复点赞");
        }
        spitService.thumbupById(spitid);
        redisTemplate.opsForValue().set("thumbup_" + userid, 1);
        return new Result(true, StatusCode.OK, "点赞成功");
      }
    }
    

      7.数据库图片


    图片

      8.开始操作

        1.添加数据
    添加数据
    成功 image.png
        2.查看
    查看所有

    相关文章

      网友评论

        本文标题:SpringBoot集成Mongodb

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