欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合MongoDB的步骤详解

程序员文章站 2023-10-28 20:01:52
项目结构:1.pom引入mongodb依赖org.springframework.boot

项目结构:

SpringBoot整合MongoDB的步骤详解

1.pom引入mongodb依赖

<dependency>
	<groupid>org.springframework.boot</groupid>
	<artifactid>spring-boot-starter-data-mongodb</artifactid>
</dependency>

2 配置application.properties

#spring.data.mongodb.host=127.0.0.1
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=books
###这种类似于关系型数据库url配置
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/books

3.创建mongodb文档映射实体类

@document(collection = "comment") //如果省略集合属性,默认为类名首字母小写
//设置复合索引
//@compoundindex(def="{'userid':1},{'nickname':-1}")
public class comment implements serializable {
 
    @id  //对应comment中的_id
    private string id;
    @field("content")//属性对应mongodb字段名,如果一致,无须该注解
    private string content;//吐槽内容
    private string articleid;//文章id
    private date publishtime;//发布日期
    @indexed  //添加一个单字段的索引
    private string userid;//发布人id
    private string nickname;//发布人昵称
    private date createdatetime;//评论的日期时间
    private integer likenum;//点赞数
    private integer replynum;//回复数
    private string state;//状态
    private string parentid;//上级id
	// 此处忽略getter与setter方法
} 

springboot中mongodb常用注解:

  1. @document

标注在实体类上,将java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。类似于hibernate的entity注解,表明由mongo来维护该集合(表)。

  1. @id

主键,不可重复,自带索引,可以在定义的列名上标注,需要自己生成并维护不重复的约束。
如果自己不设置@id主键,mongo会自动生成一个唯一主键,插入效率远高于自己设置主键。
在实际业务中不建议自己设置主键,应交给mongo自己生成,可以另外设置一个业务id,如int型字段,用自己设置的业务id来维护相关联的集合(表)。

  1. @indexed

声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。
唯一索引的话是@indexed(unique = true)。
也可以对数组进行索引,如果被索引的列是数组时,mongodb会索引这个数组中的每一个元素。
也可以对整个document进行索引,排序是预定义的按插入bson数据的先后升序排列。

  1. @compoundindex

复合索引,加复合索引后通过复合索引字段查询将大大提高速度。

  1. @field

实体类属性对应集合(表)字段名,如果一致,无须该注解

4.service业务层

commonservice,操作mongo的具体业务类

采用repository和mongotemplate两种方式来实现的;repository 提供最基本的数据访问功能,其几个子接口则扩展了一些功能。

mongotemplate核心操作类:criteria和query

  • criteria类:封装所有的语句,以方法的形式查询。
  • query类:将语句进行封装或者添加排序之类的操作。
@service
public class commentservice {
 
    @autowired
    private commentrepository commentrepository;  // 注入dao
 
    @autowired
    private mongotemplate mongotemplate;  // 注入mongodb提供的操作模板
 
	// 保存一个
    public void savecomment(comment comment){
        commentrepository.save(comment);
       // mongotemplate.save(comment);
       // mongotemplate.insert(comment);
    }
 
	// 批量保存
    public void mutilsavecomment(list<comment> list){
        commentrepository.saveall(list);
       // mongotemplate.insertall(list);
    }
 
    // 更新一个
    public void updatecomment(comment comment){
         commentrepository.save(comment);
    }
 
   	// 查询全部
    public list<comment> findcommentall(){
       // return  commentrepository.findall();
        return mongotemplate.findall(comment.class);
    }
 
    // 条件查询
    public list<comment> findcommentbycontion(query query){
        return  mongotemplate.find(query,comment.class);
    }
 
    // 查询全部并以id排序返回结果
    public list<comment> findcommentallorder(){
      //  return  commentrepository.findall(sort.by(sort.order.desc("_id")));
 
		query query=new query();
		query.with(sort.by(sort.direction.desc,"id"));
		return mongotemplate.find(query,comment.class);
    }
 
 
    // 通过id查询
    public comment findcommentbyid(string id){
        //return  commentrepository.findbyid(id).get();
        return mongotemplate.findbyid(id,comment.class);
    }
 
    /**
     * @param parentid
     * @param page
     * @param size
     * @return
     */
    public page<comment> findbyparentidpage1(string parentid, int page,int size){
        return  commentrepository.findbyparentid(parentid, pagerequest.of(page-1,size));
    }
 	
    // 方式二
    public list<comment> findbyparentidpage2(string parentid, int page,int size){
        query query=query.query(criteria.where("parentid").is(parentid));
        query.with(pagerequest.of(page-1,size));
        return  mongotemplate.find(query,comment.class);
    }
 
    // 通过id删除
    public void deletebyid(string id){
        // commentrepository.deletebyid(id);
        comment comment=new comment();
        comment.setid(id);
        mongotemplate.remove(comment);
    }
 

    // 删除全部数据
    public void deleteall(){
        commentrepository.deleteall();
    }
 
    // 批量删除
    public void deletemulti(list<comment> list){
        commentrepository.deleteall(list);
    }
 

	// 根据id更新一条文档:点赞数加1
    public void updatecommentlikenumm(string id){
		// 点赞数加一,效率低,增加id开销
		// comment comment=commentrepository.findbyid(id).get();
		// comment.setlikenum(comment.getlikenum()+1);
		// commentrepository.save(comment);
 
		// 拿到查询对象
        query query=query.query(criteria.where("_id").is(id));
        // 拿到更新对象
        update update=new update();
		// 局部更新 相当于$set
		// update.set(key,value);
		// 递增$inc
        // update.inc("likenum",1);
        update.inc("likenum");  // 指定字段自增1
        mongotemplate.updatefirst(query,update,"comment");
    }
 
    // 有条件的统计
    public long commentcount(query query){
        return mongotemplate.count(query,comment.class);
    }
}

5.dao层

dao层commentrepository 继承mongorepository,mongorepository中已经预定义了一些增删查的方法,根据jpa的命名规范可以定义一些查询方法,不需要具体实现,底层会帮你实现。

public interface commentrepository extends mongorepository<comment,string> {
  //新增按父id分页查询
    page<comment> findbyparentid(string parentid,pageable pageable);
}  

6.测试

@runwith(springrunner.class)
@springboottest
public class commentservicetest {
 
    @autowired
    private commentservice commentservice;
 
    @test
    public void savecommenttest(){  // 新增单个
        comment comment=new comment();
        //comment.setid("2");
        comment.setarticleid("777");
        comment.setcontent("添加数据测试");
        comment.setpublishtime(new date());
        comment.setuserid("1001");
        comment.setnickname("张三");
        comment.setcreatedatetime(new date());
        comment.setlikenum(1);
        comment.setreplynum(0);
        comment.setstate("1");
        comment.setparentid("0");
        commentservice.savecomment(comment);
    }
 
    @test
    public void mutilsavecomment(){  // 批量新增
        list<comment> list=new arraylist<>();
        comment comment;
        for(int i=1;i<=10;i++){
            comment=new comment();
            comment.setid(""+i);
            comment.setarticleid(""+i);
            comment.setcontent("添加数据测试"+i);
            comment.setpublishtime(new date());
            comment.setuserid("1001");
            comment.setnickname("张三");
            comment.setcreatedatetime(new date());
            comment.setlikenum(0);
            comment.setreplynum(0);
            comment.setstate("1");
            comment.setparentid("0");
            list.add(comment);
        }
        commentservice.mutilsavecomment(list);
    }
 
    @test
    public void findcommentlisttest() {  // 查询全部
        list<comment> list=commentservice.findcommentall();
        for(comment comment:list){
            system.out.println(comment);
        }
    }
 
    @test
    public void findcommentlistordertest() {  // 查全部并通对id排序
        list<comment> list=commentservice.findcommentallorder();
        for(comment comment:list){
            system.out.println(comment);
        }
    }
 

    @test
    public void findcommentbyid() {  // 通过id删除
        comment comment=commentservice.findcommentbyid("1");
        system.out.println(comment);
    }
 

    @test
    public void findbyparentid(){  // 通过父id分页查询1
        page<comment> page=commentservice.findbyparentidpage1("0",1,10);  // 第1页,每页10个
        system.out.println(page.gettotalelements());
        system.out.println(page.getcontent());
    }
 

    @test
    public void findbyparentidpage2(){  //  通过父id分页查询2
        list<comment> list=commentservice.findbyparentidpage2("0",1,10);  // 第1页,每页10个
        for(comment comment1:list){
            system.out.println(comment1);
        }
    }
 
    @test
    public void deletebyid(){  // 通过id删除评论
        commentservice.deletebyid("1");
    }
 

    @test
    public void deleteall(){  // 删除全部
        commentservice.deleteall();
    }
 
    @test
    public void deletemulti(){  // 批量删除
        list<comment> list=new arraylist<>();
        comment comment;
        for(int i=1;i<=10;i++) {
            comment = new comment();
            comment.setid("" + i);
            list.add(comment);
        }
        commentservice.deletemulti(list);
    }
 
    @test
    public void findcommentbycontion(){ // 多条件查询in
       	// 拿到查询范围
        list<string> list=new arraylist<>();
        list.add("1");
        list.add("2");
        list.add("3");
        
        // 根据范围拿到查询对象
        query query=query.query(criteria.where("_id").in(list));
 		
        // 根据查询条件拿到结果
        list<comment> list2=commentservice.findcommentbycontion(query);
        for(comment comment1:list2){
            system.out.println(comment1);
        }
    }
 
    @test
    public void findcommentcontionbygtlt(){  // 多条件查询大于2小于等于6
        // 拿到查询对象
        query query=query.query(criteria.where("likenum").gte(2).lte(6));
        // 根据查询条件拿到结果
        list<comment> list =commentservice.findcommentbycontion(query);
        for(comment comment1:list){
            system.out.println(comment1);
        }
    }
 
    @test
    public void findcommentcontionbyand(){  // 多条件查询and
        //查询对象
        query query=query.query(new criteria().andoperator(criteria.where("likenum").gte(2)
                                             ,criteria.where("state").is("1")));
        list<comment> list =commentservice.findcommentbycontion(query);
        for(comment comment1:list){
            system.out.println(comment1);
        }
    }
 
    @test
    public void findcommentcontionbyor(){ // 多条件查询or
        //查询对象
        query query=query.query(new criteria().oroperator(criteria.where("likenum").gte(2)
                                            ,criteria.where("state").is("0")));
        list<comment> list =commentservice.findcommentbycontion(query);
        for(comment comment1:list){
            system.out.println(comment1);
        }
    }
 
    @test
    public void updatecommentlikenumm(){  // 更新 点赞数加一
        commentservice.updatecommentlikenumm("1");
    }
 
    @test
    public void commentcount(){  // 统计查询
        query query=query.query(criteria.where("likenum").gte(2));  // 拿到查询器
        query query1=new query();  
        long count1=commentservice.commentcount(query);  // 查符合条件的文档个数
        long count2=commentservice.commentcount(query1);  // 查全部
        system.out.println("点赞数大于等于2的文档有======="+count1);
        system.out.println("统计总数======="+count2);
    }
}

到此已经在springboot项目中引入了mongodb,并通过mongorepository和mongotemplate两种方式来实现了基本的增删改查操。

以上就是springboot整合mongodb的步骤详解的详细内容,更多关于springboot整合mongodb的资料请关注其它相关文章!