springboot整合mongoDB的简单demo

匿名 (未验证) 提交于 2019-12-02 23:05:13

在上篇 MongoDB常用操作练习 中,我们在命令提示符窗口使用简单的mongdb的方法操作数据库,实现增删改查及其他的功能。在本篇中,我们将mongodb与spring boot进行整合,也就是在java中使用mongodb,话不多说,上代码。

一、pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>     <parent>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-parent</artifactId>         <version>1.5.19.BUILD-SNAPSHOT</version>         <relativePath/> <!-- lookup parent from repository -->     </parent>      <groupId>com.gougou</groupId>     <artifactId>springboot-demo02-mongo</artifactId>     <version>0.0.1-SNAPSHOT</version>     <name>springboot-demo02-mongo</name>     <description>Demo project for Spring Boot</description>      <properties>         <java.version>1.8</java.version>     </properties>      <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>          <!-- mongo -->         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-data-mongodb</artifactId>         </dependency>          <!-- 热部署 -->         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-devtools</artifactId>             <optional>true</optional>         </dependency>      </dependencies>      <build>         <plugins>             <plugin>                 <groupId>org.springframework.boot</groupId>                 <artifactId>spring-boot-maven-plugin</artifactId>             </plugin>         </plugins>     </build>      <repositories>         <repository>             <id>spring-snapshots</id>             <name>Spring Snapshots</name>             <url>https://repo.spring.io/snapshot</url>             <snapshots>                 <enabled>true</enabled>             </snapshots>         </repository>         <repository>             <id>spring-milestones</id>             <name>Spring Milestones</name>             <url>https://repo.spring.io/milestone</url>         </repository>     </repositories>     <pluginRepositories>         <pluginRepository>             <id>spring-snapshots</id>             <name>Spring Snapshots</name>             <url>https://repo.spring.io/snapshot</url>             <snapshots>                 <enabled>true</enabled>             </snapshots>         </pluginRepository>         <pluginRepository>             <id>spring-milestones</id>             <name>Spring Milestones</name>             <url>https://repo.spring.io/milestone</url>         </pluginRepository>     </pluginRepositories>  </project>
View Code

 

二、application.properties

# 配置tomcat的端口号 server.port=8081  # mongo spring.data.mongodb.uri=mongodb://localhost:27017/test
View Code

 

三、实体类Student

package com.gougou.student;   public class Student {      private String id;      private String name;      private Integer age;      private Boolean gender;      public String getId() {         return id;     }      public void setId(String id) {         this.id = id;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public Integer getAge() {         return age;     }      public void setAge(Integer age) {         this.age = age;     }      public Boolean getGender() {         return gender;     }      public void setGender(Boolean gender) {         this.gender = gender;     }      @Override     public String toString() {         return "Student{" +                 "id='" + id + '\'' +                 ", name='" + name + '\'' +                 ", age=" + age +                 ", gender=" + gender +                 '}';     }      public Student(){     }      public Student(String name, Integer age, Boolean gender) {         this.name = name;         this.age = age;         this.gender = gender;     }  }
View Code

 

四、仓库StudentRepository

package com.gougou.student;  import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query;  import java.util.List;   public interface StudentRepository extends MongoRepository<Student,String> {      /**      * 根据实体属性进行精确查询:find + By + 属性名(首字母大写)      */     List<Student> findByName(String name);      List<Student> findByAge(Integer age);      List<Student> findByGender(Boolean gender);      /**      * 根据实体属性进行模糊查询:find + By + 属性名(首字母大写) + Like      */     List<Student> findByNameLike(String name);      /**      * 根据实体属性进行模糊查询+分页:find + By + 属性名(首字母大写) + Like      */     Page<Student> findByNameLike(String name, PageRequest pageRequest);      /**      * 查询所有数据,同时指定返回的键。      *      * 不能使用仓库中自带的findAll()方法了。我们可以查询所有id不为空的数据,同时指定返回的键。      * 当我们需要根据一个key且该key不为空进行查询,方法名的定义规则为:find + By + 属性名(首字母大写) + NotNull。      *      * 指定返回的键:也就是说当我们进行带分页的模糊查询时,不想返回数据库中的所有字段,只是返回一部分字段,若想指定返回的键,我们需要在      * PersonRepository中添加方法,同时使用注解@Query。其中value是查询的条件,?0这个是占位符,对应着方法中参数中的第一个参数,如果对应的是      * 第二个参数则为?1。fields是我们指定的返回字段,其中id是自动返回的,不用我们指定      */     @Query(value = "{'_id':{'$ne':null}}",fields = "{'name':1}")     Page<Student> findByIdNotNull(Pageable pageable);  }
View Code

 

五、service实现类StudentServiceImpl

package com.gougou.student;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service;  import java.util.List;   @Service public class StudentServiceImpl implements StudentService {      @Autowired     private StudentRepository studentRepository;      /**      * @function 插入单条数据      * @param student      */     @Override     public void insert(Student student) {         studentRepository.insert(student);     }      /**      * @function 批量插入数据      */     @Override     public void insertByList(List<Student> studentList) {         studentRepository.insert(studentList);     }      /**      * @function 无条件计数      * @return      */     @Override     public int count() {         return (int)studentRepository.count();     }      /**      * @function 无条件查询所有的数据      * @return      */     @Override     public List<Student> queryAll() {         return studentRepository.findAll();     }      /**      * @function 无条件查询分页      * @return      */     @Override     public Page<Student> queryByPage(int page, int rows) {         PageRequest pageRequest = new PageRequest(page,rows);         return studentRepository.findAll(pageRequest);     }      /**      * 根据实体属性进行精确查询      */     @Override     public List<Student> queryByName(String name) {         return studentRepository.findByName(name);     }      @Override     public List<Student> queryByAge(Integer age) {         return studentRepository.findByAge(age);     }      @Override     public List<Student> queryByGender(Boolean gender) {         return studentRepository.findByGender(gender);     }      /**      * 根据实体属性进行模糊查询      */     @Override     public List<Student> queryByNameLike(String name) {         return studentRepository.findByNameLike(name);     }      /**      * 根据实体属性进行模糊查询并分页      * @return      */     @Override     public Page<Student> queryByNameLikeAndPage(int page,int rows,String name) {         PageRequest pageRequest = new PageRequest(page,rows);         return studentRepository.findByNameLike(name,pageRequest);     }  }
View Code

 

六、servie接口

package com.gougou.student;  import org.springframework.data.domain.Page;  import java.util.List;   public interface StudentService {      /**      * @function 插入单条数据      * @param student      */     void insert(Student student);      /**      * @function 批量插入数据      */     void insertByList(List<Student> studentList);      /**      * @function 无条件计数      * @return      */     int count();      /**      * @function 无条件查询所有的数据      * @return      */     List<Student> queryAll();      /**      * @function 无条件查询分页      * @return      */     Page<Student> queryByPage(int page,int rows);      /**      * 根据实体属性进行精确查询      */     List<Student> queryByName(String name);     List<Student> queryByAge(Integer age);     List<Student> queryByGender(Boolean gender);      /**      * 根据实体属性进行模糊查询      */     List<Student> queryByNameLike(String name);      /**      * 根据实体属性进行【模糊+分页】查询      */     Page<Student> queryByNameLikeAndPage(int page,int rows,String name);  }
View Code

 

七、controller

package com.gougou.student;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;  import java.util.ArrayList; import java.util.List;   @RestController @RequestMapping(value = "student") public class StudentController {      @Autowired     private StudentService studentService;       /**      * 插入一条数据      * @return      */     @RequestMapping(value = "insert")     public int insert(){         Student student = new Student("张三",25,true);         studentService.insert(student);         return 1;     }      /**      * 插入一条数据      * @return      */     @RequestMapping(value = "insertByList")     public int insertByList(){         List<Student> students = new ArrayList<>(10);          Student student = null;         for (int i = 0;i<10;i++){             student = new Student("李斯"+i,i+15,i%2==0?true:false);             students.add(student);         }         studentService.insertByList(students);         return 1;     }      /**      * 无条件的数据统计      */     @RequestMapping(value="count")     public int count(){         return studentService.count();     }      /**      * @function 无条件查询所有的数据      * @return      */     @RequestMapping(value="queryAll")     public List<Student> queryAll(){         return studentService.queryAll();     }      /**      * @function 无条件查询分页      * @return      */     @RequestMapping(value="queryByPage")     public Page<Student> queryByPage(Integer page, Integer rows){         if(page == null || page <0){             page = 0;         }         if(rows == null || rows < 0){             rows = 5;         }         return studentService.queryByPage(page,rows);     }      /**      * 根据实体属性进行精确查询      */     @RequestMapping(value = "queryByName")     public List<Student> queryByName(String name){         return studentService.queryByName(name);     }      @RequestMapping(value = "queryByAge")     public List<Student> queryByAge(Integer age){         return studentService.queryByAge(age);     }      @RequestMapping(value = "queryByGender")     public List<Student> queryByGender(Boolean gender){         return studentService.queryByGender(gender);     }      /**      * 根据实体属性进行模糊查询      */     @RequestMapping(value = "queryByNameLike")     public List<Student> queryByNameLike(String name){         return studentService.queryByNameLike(name);     }      /**      * 模糊查询加分页      */     @RequestMapping(value = "queryByNameLikeAndPage")     public Page<Student> queryByNameLikeAndPage(Integer page,Integer rows,String name){         if(page == null || page <0){             page = 0;         }         if(rows == null || rows < 0){             rows = 5;         }         return studentService.queryByNameLikeAndPage(page,rows,name);     }  }
View Code

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!