SpringBoot整合MongoDB快速入门+MongoDB分页

SpringBoot整合MongoDB快速入门

1、导入依赖

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
        dependency>
		
		<dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

2、新建实体类

注:

1、使用了lombock

2、@Document(collection = “letters”)

3、@Id :

@Id
private String id; //对应主键 _id

collection=“letters” 表示你要存入到MongoDB 的那个集合中:这里就是指letters集合

SpringBoot整合MongoDB快速入门+MongoDB分页_第1张图片

@Document(collection = "letters")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Letter {
    @Id
    private String id;
    private Integer userid;
    private String nickname;
    private String title;
    private String content;
    private String ctime;
    private String stime;
}

3、编写Service

SpringBoot整合MongoDB快速入门+MongoDB分页_第2张图片

package cn.xhubbq.service.letter;
import cn.xhubbq.pojo.letter.Letter;
import com.mongodb.client.result.DeleteResult;
import java.util.List;

/**
 * Author:甲粒子
 * Date: 2021/11/24
 * Description:
 */
public interface ILetterService {
    //写信
    Letter addLetter(Letter letter);
    //删除
    DeleteResult deleteLetterById(String id);
    //查询所有
    List<Letter> selectAllLetters();
    //分页查询
    List<Letter> selectLettersByPage(int curPage,int pageSize);
    //查总数
    long letterCount();

}
package cn.xhubbq.service.letter;
import cn.xhubbq.pojo.letter.Letter;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;
import java.util.List;

/**
 * Author:甲粒子
 * Date: 2021/11/24
 * Description:
 */
@Service
public class LetterServiceImpl implements ILetterService{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Letter addLetter(Letter letter) {
        return mongoTemplate.insert(letter);
    }

    @Override
    public List<Letter> selectAllLetters() {
        return mongoTemplate.findAll(Letter.class,"letters");
    }

    @Override
    public List<Letter> selectLettersByPage(int curPage, int pageSize) {
        Query query=new Query();//Query是条件构造器
        //从第1页开始
        //分页查询,query.skip((curPage-1)*size).limit(size)表示跳过(当前页-1)*每页的大小条数据,输出size条数据
        return mongoTemplate.find(query.skip((curPage-1)*pageSize).limit(pageSize),Letter.class);
    }

    @Override
    public DeleteResult deleteLetterById(String id) {
        Query query=new Query(Criteria.where("_id").is(id));
        return mongoTemplate.remove(query,Letter.class);
    }

    @Override
    public long letterCount() {
        Query query=new Query();
        return mongoTemplate.count(query,Letter.class);
    }
}

说明:

 Query query=new Query(Criteria.where("_id").is(id));

这很好理解: 查询 _id == id 的文档

也可以:使用 .and() 连接多个条件

 Query query=new Query(Criteria.where("_id").is(id).and().where("name").is("你的名字"));

remove会返回一个DeleteResult 里面包含了删除数据的条数,可一通过 ’ . ’ 的方式来验证。

mongoTemplate.remove(query,Letter.class);

分页查询需要新建一个实体类来控制:

package cn.xhubbq.pojo.page;

import cn.xhubbq.pojo.letter.Letter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * Author:甲粒子
 * Date: 2021/11/24
 * Description:信的页面
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LetterPage {
    private long totalpage;//总页数
    private long currentpage;//当前页
    private long totalcount;//总数
    private long pagesize;//页面大小
    private List<Letter> letters;
    public void setPagesize(int psize){
        this.pagesize=psize;
        totalpage=totalcount%pagesize!=0?totalcount/pagesize+1:totalcount/pagesize;//这段代码一定要在pagesize复制后执行
    }
}

4、编程Controller来测试

package cn.xhubbq.controller.letter;
import cn.hutool.extra.ssh.JschRuntimeException;
import cn.xhubbq.pojo.letter.Letter;
import cn.xhubbq.pojo.page.LetterPage;
import cn.xhubbq.service.letter.LetterServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:甲粒子
 * Date: 2021/11/24
 * Description:
 */
@RestController
public class LetterController {
    @Autowired
    private LetterServiceImpl letterService;
    private static final int PAGE_SIZE=5;

    @ResponseBody
    @RequestMapping("/addLetter")
    public Object addLetter(){
        Letter letter=new Letter("xadgjadbhjas",1,"小翟","titlename","content__is","创建时间","发布时间");
        List<Letter> lst=new ArrayList<>();
        for(int i=0;i<10;++i){
            lst.add(new Letter("xadgjadbhjas"+('a'*i),i+1,"小翟"+i,"titlename"+i,"content__is","创建时间","发布时间"));
        }
        for (Letter let : lst) {
            letterService.addLetter(let);
        }
        return lst;
    }
    @ResponseBody
    @RequestMapping("/findLetters")
    public List<Letter> findLetter(){
        return letterService.selectAllLetters();
    }

    @ResponseBody
    @RequestMapping("/letterPage/{curPage}")
    public Object letterPage(@PathVariable int curPage){
        LetterPage letterPage=new LetterPage();
        letterPage.setCurrentpage(curPage);
        letterPage.setTotalcount(letterService.letterCount());//查总数
        letterPage.setPagesize(PAGE_SIZE);

        List<Letter> letters=letterService.selectLettersByPage(curPage,PAGE_SIZE);
        letterPage.setLetters(letters);
        return letterPage;
    }

    @ResponseBody
    @RequestMapping("/deleteLetter/{id}")
    public String deleteLetter(@PathVariable String id){
        Map<String,Object> map=new HashMap<>();
        if(id!=null){
            DeleteResult deleteResult = letterService.deleteLetterById(id);
            if (deleteResult!=null){
                return JSONObject.toJSONString(deleteResult);
            }
            map.put("state",0);
            map.put("info","error");
            return JSONObject.toJSONString(map);
        }
        map.put("state",0);
        map.put("info","error");
        return JSONObject.toJSONString(map);
    }
}

说明:

使用了restful风格:也就是访问的时候不是 用问号传参 而是:

例如: @RequestMapping("/deleteLetter/{id}")

是:localhost:8080/deleteLetter/1

而不是:localhost:8080/deleteLetter?id=1

使用阿里巴巴的fastJson:

依赖:

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.14version>
        dependency>

云服务器上安装MongoDB

你可能感兴趣的:(中间件系列(Redis,MongoDB等),mongodb,nosql,数据库)