在IDEA里面使用新建一个maven项目,

项目的结构是如图所示:(注意:springboot 项目中所有的组件必须位于application同级或者子包下才会被扫描到,不然就会报上面的错!)

导入相关的jar包

1、加入jar包依赖

    <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency></dependencies>

2、在resource文件夹目录下新建application.properites文件

spring.data.mongodb.uri= mongodb://localhost:27017/ceshi

3、新建model下面的类

下面新建的类里面的get,set,toString方法自己加一下呀,这边就不展示了

(1)、Person实体类

public class Person implements Serializable {@Idprivate long personId;private String name;private String address;private int age;private TypeEnum type;
}

(2)、Teacher实体类

public class Teacher extends  Person {private String likeStudent;private String teacheCourse;
}

(3)、Student实体类

public class Student extends Person {private String likeSport;private String likeBook;private String school;
}

(4)、TypeEnum枚举类

public enum TypeEnum {STUDENT("student", "学生"),TEACHER("teacher", "教师");private final String value;private final String text;public String getValue() {return value;}public String getText() {return text;}TypeEnum(String value, String text) {this.value = value;this.text = text;}
}

4、继承MongoRepository的接口

MongoRepository继承了这个接口可以发现没有更新的方法,所以后面的文章将使用MongoTemplate、MongoOperations来操作是数据库。

repository支持了简单的查询和新增、删除。使用spring data的方法不用实现接口,直接 根据方法名,或者自定义的条件Query来操作。

(1)、StudentRepository

package com.mongodb.demo.repository;import com.mongodb.demo.model.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;public interface StudentRepository extends MongoRepository<Student, Long> {Student findByPersonId(Long personId);//分页查询满足条件:name = name and age >= age limit pageable@Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}")Page<Student> findByNameAndAge2(String name, int age, Pageable pageable);int deleteByPersonId(Long personId);//删除满足条件:age >= age1 and age <= age2@Query("{\"age\":{\"$gte\":?0},\"$lte\":?1}")int deleteByAge2(int age1,int age2);//分页查询满足条件:name = name and age >= age limit pageable,只会查询相互personId和age的值@Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}",fields = "{\"personId\":1,\"age\":1}")Page<Student> findByAge2(String name, int age, Pageable pageable);}

(2)、TeacherRepository

package com.mongodb.demo.repository;import com.mongodb.demo.model.Teacher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;public interface TeacherRepository extends MongoRepository<Teacher, Long> {Teacher findByPersonId(Long personId);//分页查询满足条件:name = name and age >= age limit pageable@Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}")Page<Teacher> findByNameAndAge2(String name, int age, Pageable pageable);int deleteByPersonId(Long personId);//删除满足条件:age <= age1 and age >= age2@Query("{\"age\":{\"$lte\":?0},\"$gte\":?1}")int deleteByAge2(int age1,int age2);//分页查询满足条件:name = name and age >= age limit pageable,只会查询相互personId和age的值@Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}",fields = "{\"personId\":0,\"address\":0}")Page<Teacher> findByAge2(String name, int age, Pageable pageable);
}

5、spring boot的启动类

DemoApplication启动类,启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件

package com.mongodb.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;@SpringBootApplication
@ServletComponentScan
public class DemoApplication {public static void main(String[] args) throws Exception {SpringApplication.run(DemoApplication.class,args);}
}

6、ApplicationStartup监听类

package com.mongodb.demo;import com.mongodb.demo.model.Student;
import com.mongodb.demo.model.Teacher;
import com.mongodb.demo.model.TypeEnum;
import com.mongodb.demo.repository.StudentRepository;
import com.mongodb.demo.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;/*
* 监听springboot启动类是否启动,启动就执行数据操作
* */
@Configuration
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {@Autowiredprivate StudentRepository studentRepository;@Autowiredprivate TeacherRepository teacherRepository;public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {  //项目启动后,执行启动消费者方法try {//新增数据操作insert();//查找数据操作分页数据findByNameAndAge();//删除数据delete();} catch (Exception e) {e.printStackTrace();}}//新增数据public void insert(){Student student = new Student();student.setPersonId(20180101L);student.setType(TypeEnum.STUDENT);student.setAge(22);student.setAddress("广东省深圳市福田区");student.setName("张三");student.setLikeBook("你的孤独虽败犹荣");student.setLikeSport("羽毛球");student.setSchool("某某大学");Teacher teacher = new Teacher();teacher.setPersonId(20180101L);teacher.setType(TypeEnum.TEACHER);teacher.setAge(32);teacher.setAddress("广东省深圳市福田区");teacher.setName("张三丰");teacher.setTeacheCourse("JavaEE");teacher.setLikeStudent("张三");for(int i = 0 ;i < 15 ; i++){student.setAge(student.getAge()-i/2);student.setPersonId(student.getPersonId()+i);studentRepository.save(student);student.setAge(teacher.getAge()+i/2);teacher.setPersonId(teacher.getPersonId()+i);teacherRepository.save(teacher);}System.out.println("************************");System.out.println("新增学生的数据数量为:"+studentRepository.findAll().size());System.out.println("新增老师的数据数量为:"+teacherRepository.findAll().size());}public void findByNameAndAge(){Pageable pageable = PageRequest.of(0,5);//获取分页数据,每页5条数,取第0页的数据,Page<Student> studentPage = studentRepository.findByNameAndAge2("张三",20,pageable);Page<Student> studentPage1 = studentRepository.findByAge2("张三",20,pageable);for(Student student : studentPage){System.out.println("+++++++++++++:"+student.toString());}for(Student student : studentPage1){System.out.println("-------------:"+student.toString());}Pageable pageable1 = PageRequest.of(1,3);//获取分页数据,每页3条数,取第1页的数据,Page<Teacher> teacherPage =teacherRepository.findByNameAndAge2("张三丰",30,pageable1);Page<Teacher> teacherPage1 =teacherRepository.findByAge2("张三丰",30,pageable1);for(Teacher teacher : teacherPage){System.out.println("+++++++++++++:"+teacher.toString());}for(Teacher teacher : teacherPage1){System.out.println("-------------:"+teacher.toString());}}public void delete(){try {studentRepository.deleteByPersonId(20180101L);System.out.println("学生ID为20180101的数据删除成功");System.out.println("删除后学生数据数量为:"+studentRepository.findAll().size());teacherRepository.deleteByPersonId(20180101L);System.out.println("教师ID为20180101的数据删除成功");System.out.println("删除后教师数据数量为:"+teacherRepository.findAll().size());}catch (Exception e){System.err.println("数据删除失败"+e.getMessage());}}}

7、测试类

要测试就用测试类,其实测试类就是单独自己去启动启动类来加载执行数据操作

import com.mongodb.demo.DemoApplication;
import com.mongodb.demo.model.Student;
import com.mongodb.demo.model.Teacher;
import com.mongodb.demo.model.TypeEnum;
import com.mongodb.demo.repository.StudentRepository;
import com.mongodb.demo.repository.TeacherRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*
* 测试类
* */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class StudentRepositoryTest {private final Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate StudentRepository studentRepository;@Autowiredprivate TeacherRepository teacherRepository;@Testpublic void test() throws Exception {Student student = new Student();student.setPersonId(20180101L);student.setType(TypeEnum.STUDENT);student.setAge(22);student.setAddress("广东省深圳市福田区");student.setName("张三");student.setLikeBook("你的孤独虽败犹荣");student.setLikeSport("羽毛球");student.setSchool("某某大学");studentRepository.save(student);System.out.println("************************");Teacher teacher = new Teacher();teacher.setPersonId(20180102L);teacher.setType(TypeEnum.TEACHER);teacher.setAge(32);teacher.setAddress("广东省深圳市福田区");teacher.setName("张三丰");teacher.setTeacheCourse("JavaEE");teacher.setLikeStudent("张三");teacherRepository.save(teacher);System.out.println("************************");Student student1 = studentRepository.findByPersonId(student.getPersonId());Teacher teacher1 = teacherRepository.findByPersonId(teacher.getPersonId());System.out.println("新增学生的数据为:"+student1.toString());System.out.println("新增老师的数据为:"+teacher1.toString());}}

8、运行结果

下面的斜体就是运行结果:,由于截图不清晰就用了斜体来展示:

************************
新增学生的数据数量为:15
新增老师的数据数量为:15
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180101, name='张三', address='广东省深圳市福田区', age=22, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180102, name='张三', address='广东省深圳市福田区', age=32, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180104, name='张三', address='广东省深圳市福田区', age=31, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180107, name='张三', address='广东省深圳市福田区', age=32, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180111, name='张三', address='广东省深圳市福田区', age=31, type=STUDENT}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180101, name='null', address='null', age=22, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180102, name='null', address='null', age=32, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180104, name='null', address='null', age=31, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180107, name='null', address='null', age=32, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180111, name='null', address='null', age=31, type=null}
+++++++++++++:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=20180107, name='张三丰', address='广东省深圳市福田区', age=32, type=TEACHER}
+++++++++++++:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=20180111, name='张三丰', address='广东省深圳市福田区', age=32, type=TEACHER}
+++++++++++++:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=20180116, name='张三丰', address='广东省深圳市福田区', age=32, type=TEACHER}
-------------:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=0, name='张三丰', address='null', age=32, type=TEACHER}
-------------:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=0, name='张三丰', address='null', age=32, type=TEACHER}
-------------:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=0, name='张三丰', address='null', age=32, type=TEACHER}
学生ID为20180101的数据删除成功
删除后学生数据数量为:14
教师ID为20180101的数据删除成功
删除后教师数据数量为:14

使用spring data建议使用IDEA来写,方法都是有提示的,可以减少错误。

本案例下载地址:https://download.csdn.net/download/qq_26584263/10661868

《………………………………………………菜鸟起飞中,请各位走过路过的多多指教……………………………………》

spring data使用操作mongodb数据库 springboot相关推荐

  1. SpringBoot 实战 (八) | 使用 Spring Data JPA 访问 Mysql 数据库

    微信公众号:一个优秀的废人 如有问题或建议,请后台留言,我会尽力解决你的问题. 前言 如题,今天介绍 Spring Data JPA 的使用. 什么是 Spring Data JPA 在介绍 Spri ...

  2. PHP操作mongodb数据库操作类

    最近的项目开发中使用的数据库是mongodb数据库,因为小编的公司也是刚刚使用mongodb数据库,所以之前没有封装好的mongodb数据库操作类拿来使用,所以小编在项目中自己封装了一个mongodb ...

  3. Lua 操作 MongoDB 数据库实例

    最近有个工作是使用Nginx + Lua实现一个操作MongoDB数据库的API,主要实现其count和query功能.之前没有写过Lua,于是也就勉强着上手,在cloudwu的 lua-mongo ...

  4. Nodejs 操作 MongoDb 数据库

    一.在 Nodejs 中使用 Mongodb 在前面的博文我们给大家讲了如何使用命令操作 Mongodb,这篇博文开始我们给大家讲解一 下如何使用 Nodejs 来操作 Mongodb 数据库 Nod ...

  5. 使用mongoose 在 Node中操作MongoDB数据库

    MongoDB 关系型和非关系型数据库 关系型数据库(表就是关系,或者说表与表之间存在关系). 所有的关系型数据库都需要通过sql语言来操作 所有的关系型数据库在操作之前都需要设计表结构 而且数据表还 ...

  6. tp5连接mongo和mysql_tp5(thinkPHP5)操作mongoDB数据库的方法

    本文实例讲述了tp5(thinkPHP5)操作mongoDB数据库的方法.分享给大家供大家参考,具体如下: 1.通过composer安装 composer require mongodb/mongod ...

  7. node用mongodb还是mysql,Node 操作 mongoDB 数据库和 mySQL数据库

    下载安装 MongoDB image.png 直接点击下载就行了 image.png 安装 mongodb 一直点击下一步,知道这一步 image.png 选中自己选择想安装的目录路径(选择安装的目录 ...

  8. eggjs使用egg-mongoose操作MongoDB数据库

    eggjs使用egg-mongoose操作MongoDB数据库 npm安装mongoose依赖 npm install egg-mongoose --save 配置config/plugin.js和c ...

  9. Python 操作 MongoDB 数据库!

    作者 |黄伟呢 来源 |数据分析与统计学之美 MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. 先来看看MySQL与MongoDB 概念区别 ...

最新文章

  1. 2018CTF大赛学习
  2. 在2008 server上部署域
  3. VTK:PolyData之ExtractSelection
  4. vue 如何获取图片的原图尺寸_公众号封面图片尺寸是多少?如何在公众号里制作封面图?...
  5. VMware 安装kali——linux
  6. 数码管显示实验一 编写程序让8只数码管同时显示零
  7. 计算正方形面积和周长_小学三年级数学下册长方形和正方形面积计算练习题(无答案)...
  8. 如何判断单链表是否存在环
  9. html 字体显示倒影,用CSS3的box-reflect设置文字倒影效果的方法讲解
  10. 一个简单的基于 DirectShow 的播放器 1(封装类)
  11. 在Paint事件中绘制控件(边框)
  12. 《iOS取证实战:调查、分析与移动安全》一3.6 iPhone操作系统
  13. 计算机连接拒绝访问,打印机拒绝访问,手把手教你打印机拒绝访问无法连接
  14. unbuntu下载编译chromium
  15. DataGrid Bind Checkbox....
  16. 我们来试着解答一下下面的题目(8)(DP/多重部分和)
  17. java anymatch_Java Stream anyMatch() API
  18. 任天堂Switch便携底座方案
  19. 机器学习python中train_test_split()函数进行数据集分割
  20. 为什么说新一代华为MateBook E是当下最能打的二合一装备

热门文章

  1. 软件学院宣传视频制作日志——后期制作阶段
  2. 二本,终于拿到腾讯阿里offer了,翻牌!
  3. dedecms 标签用法
  4. python3.7 scrapy crawl 报错
  5. 快速学习-电影推荐系统设计(数据源解析)
  6. 怎么给WPS表格添加批注提示
  7. 仿佛兮若轻云之蔽月,飘飘兮若流风之回雪
  8. 【AI绘画】美到我的心巴上
  9. form表单target属性运用
  10. WPF前端:按钮控件属性Button