在上篇 MongoDB經常使用操做練習 中,咱們在命令提示符窗口使用簡單的mongdb的方法操做數據庫,實現增刪改查及其餘的功能。在本篇中,咱們將mongodb與spring boot進行整合,也就是在java中使用mongodb。固然了,這個只是一個簡單到不能再簡單的demo,我只是爲了練手。實際項目中應用確定比這複雜多了。話很少說,上代碼。html
1、pom.xmljava
在這裏我集成的依賴有web,test,mongodb,devtools。其中devtools是熱部署,它會自動的編譯代碼。若是不加入這個依賴,手動編譯也是能夠的,我主要是嫌手動編譯麻煩就這樣作了。web
<?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>
2、application.propertiesspring
這裏我是修改了tomcat的端口號,若是你的8080端口沒佔用,能夠註釋掉這段代碼。mongodb
# 配置tomcat的端口號 server.port=8081 # mongo(未設置密碼) spring.data.mongodb.uri=mongodb://localhost:27017/test # mongo(設置密碼) #spring.data.mongodb.uri=mongodb://user:password@localhost:27017/mydb
3、實體類Student數據庫
這裏在實體類的id屬性上你能夠選擇性的加上「@Id」註解,因爲在不加此註解時,mongodb會自動生成「_id」,而加上此註解,不但須要手動指定主鍵,並且插入效率遠遠低於不加註解的狀況。因此在這裏我沒有使用註解。apache
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; } }
4、倉庫StudentRepositorytomcat
寫一個接口,繼承MongoRepository,這個接口有了基本的CURD的功能。若是你想自定義一些查詢,好比根據name來查詢,或者根據age來查詢,只須要定義一個方法便可。注意name嚴格按照存入的mongodb的字段對應。在典型的Java的應用程序,寫這樣一個接口的方法,須要本身實現,可是在springboot中,你只須要按照格式寫一個接口名和對應的參數就能夠了,由於springboot已經幫你實現了。springboot
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); }
5、service實現類StudentServiceImplapp
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); } }
6、servie接口StudentService
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); }
7、StudentController
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); } }