spring-boot整合mongodb的案例

时间:2021-02-02 02:37:11

1.简介

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

2.运行环境

开发工具:intellij idea

JDK版本:1.8

项目管理工具:Maven 4.0.0

3.Maven Plugin管理

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.goku</groupId>
 8     <artifactId>spring-boot-mongodb</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10 
11     <parent>
12         <groupId>org.springframework.boot</groupId>
13         <artifactId>spring-boot-starter-parent</artifactId>
14         <version>1.5.6.RELEASE</version>
15     </parent>
16 
17 
18     <dependencies>
19         <dependency>
20             <groupId>org.springframework.boot</groupId>
21             <artifactId>spring-boot-starter-web</artifactId>
22         </dependency>
23         <dependency>
24             <groupId>org.springframework.boot</groupId>
25             <artifactId>spring-boot-starter-test</artifactId>
26             <scope>test</scope>
27         </dependency>
28         <dependency>
29             <groupId>org.springframework.boot</groupId>
30             <artifactId>spring-boot-devtools</artifactId>
31             <optional>true</optional>
32         </dependency>
33         <dependency>
34             <groupId>org.springframework.boot</groupId>
35             <artifactId>spring-boot-starter-data-mongodb</artifactId>
36         </dependency>
37     </dependencies>
38 
39     <build>
40         <plugins>
41             <plugin>
42                 <groupId>org.springframework.boot</groupId>
43                 <artifactId>spring-boot-maven-plugin</artifactId>
44                 <configuration>
45                     <fork>true</fork>
46                 </configuration>
47             </plugin>
48         </plugins>
49     </build>
50 
51 
52 </project>
View Code

4.application.properties编写

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
1 spring.data.mongodb.uri= mongodb://localhost:27017/goku_db1
View Code

5.DemoApplication启动类编写

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
 1 package com.goku.demo;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.boot.web.servlet.ServletComponentScan;
 6 
 7 /**
 8  * Created by nbfujx on 2017/11/20.
 9  */
10 // Spring Boot 应用的标识
11 @SpringBootApplication
12 @ServletComponentScan
13 public class DemoApplication {
14 
15     public static void main(String[] args) {
16         // 程序启动入口
17         // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
18         SpringApplication.run(DemoApplication.class,args);
19     }
20 }
View Code

6.User编写

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
package com.goku.demo.model;

import org.springframework.data.annotation.Id;

import java.io.Serializable;

/**
 * Created by nbfujx on 2017-12-07.
 */
public class User implements Serializable {

    private static final long serialVersionUID = -1L;

    @Id
    private Long id;
    private String username;
    private Integer age;

    public User(Long id, String username, Integer age) {
        this.id = id;
        this.username = username;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "\"User:{\"id\":\""+id+"\",\"username\":\""+username+"\",\"age\":\""+age+"\"}\"";
    }
}
View Code

7.UserRepository编写

与HibernateRepository类似,通过继承MongoRepository接口,我们可以非常方便地实现对一个对象的增删改查,要使用Repository的功能,先继承MongoRepository<T, TD>接口,其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。之后在service中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。

但是MongoRepository实现了的只是最基本的增删改查的功能,要想增加额外的查询方法,可以按照以下规则定义接口的方法。自定义查询方法,格式为“findBy+字段名+方法后缀”,方法传进的参数即字段的值,此外还支持分页查询,通过传进一个Pageable对象,返回Page集合。

下面是支持的查询类型,每三条数据分别对应:(方法后缀,方法例子,mongodb原生查询语句)

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
 1 package com.goku.demo.repository;
 2 
 3 import com.goku.demo.model.User;
 4 import org.springframework.data.domain.Page;
 5 import org.springframework.data.domain.Pageable;
 6 import org.springframework.data.mongodb.repository.MongoRepository;
 7 import org.springframework.data.mongodb.repository.Query;
 8 
 9 import java.util.List;
10 
11 /**
12  * Created by nbfujx on 2017-12-08.
13  */
14 public interface UserRepository extends MongoRepository<User, Long> {
15 
16     /**
17      * Like(模糊查询)
18      * {"username" : name} ( name as regex)
19      * */
20     List<User> findByUsernameLike(String username);
21 
22     /**
23      * Like(模糊查询)
24      * {"username" : name}
25      * */
26     List<User> findByUsername(String username);
27 
28     /**
29      * GreaterThan(大于)
30      * {"age" : {"$gt" : age}}
31      * */
32     List<User> findByAgeGreaterThan(int age);
33     /**
34      * LessThan(小于)
35      * {"age" : {"$lt" : age}}
36      * */
37     List<User> findByAgeLessThan(int age);
38     /**
39      * Between(在...之间)
40      * {{"age" : {"$gt" : from, "$lt" : to}}
41      * */
42     List<User> findByAgeBetween(int from, int to);
43 
44     /**
45      * IsNotNull, NotNull(是否非空)
46      *  {"username" : {"$ne" : null}}
47      * */
48     List<User> findByUsernameNotNull();
49 
50     /**
51      * IsNull, Null(是否为空)
52      *   {"username" : null}
53      * */
54     List<User> findByUsernameNull();
55 
56 
57     /**
58      * Not(不包含)
59      *    {"username" : {"$ne" : name}}
60      * */
61     List<User> findByUsernameNot(String name);
62 
63 
64 
65     /**
66      *  Near(查询地理位置相近的)
67      *  {"location" : {"$near" : [x,y]}}
68      * */
69      // findByLocationNear(Point point)
70 
71 
72     /**
73      * Within(在地理位置范围内的)
74      *   {"location" : {"$within" : {"$center" : [ [x, y], distance]}}}
75      * */
76     //findByLocationWithin(Circle circle)
77 
78 
79     /**
80      *   Within(在地理位置范围内的)
81      *     {"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}
82      * */
83    // findByLocationWithin(Box box)
84 
85     
86 
87 }
View Code

尽管以上查询功能已经很丰富,但如果还不能满足使用情况的话可以用一下方法---基于mongodb原本查询语句的查询方式。

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
1     @Query("{\"username\":{\"$regex\":?0}, \"age\": ?1}")
2     Page<User> findByNameAndAgeRange(String name,int age,Pageable page);
3 
4     @Query(value="{\"username\":{\"$regex\":?0},\"age\":{\"$gte\":?1,\"$lte\": ?2}}")
5     Page<User> findByNameAndAgeRange2(String name,int ageFrom,int ageTo,Pageable page);
6 
7     @Query(value="{\"username\":{\"$regex\":?0},\"age\":{\"$gte\":?1,\"$lte\": ?2}}",fields="{\"username\" : 1, \"age\" : 1}")
8     Page<User> findByNameAndAgeRange3(String name,int ageFrom,int ageTo,Pageable page);
View Code

8.UserRepositoryTest测试编写

spring-boot整合mongodb的案例spring-boot整合mongodb的案例
  1 package test.com.goku.repository;
  2 
  3 import com.goku.demo.DemoApplication;
  4 import com.goku.demo.model.User;
  5 import com.goku.demo.repository.UserRepository;
  6 import org.junit.Assert;
  7 import org.junit.Before;
  8 import org.junit.Test;
  9 import org.junit.runner.RunWith;
 10 import org.slf4j.Logger;
 11 import org.slf4j.LoggerFactory;
 12 import org.springframework.beans.factory.annotation.Autowired;
 13 import org.springframework.boot.test.context.SpringBootTest;
 14 import org.springframework.data.domain.Page;
 15 import org.springframework.data.domain.PageRequest;
 16 import org.springframework.data.domain.Pageable;
 17 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 18 
 19 import java.util.List;
 20 
 21 /**
 22  * Created by nbfujx on 2017-12-08.
 23  */
 24 @RunWith(SpringJUnit4ClassRunner.class)
 25 @SpringBootTest(classes = DemoApplication.class)
 26 public class UserRepositoryTest {
 27 
 28     private final Logger logger = LoggerFactory.getLogger(getClass());
 29 
 30     @Autowired
 31     private UserRepository userRepository;
 32 
 33     @Before
 34     public void setUp() {
 35         //userRepository.deleteAll();
 36     }
 37 
 38     @Test
 39     public void test() throws Exception {
 40 
 41         // 创建10个User,并验证User总数
 42         userRepository.save(new User(1L, "didi", 30));
 43         userRepository.save(new User(2L, "mama", 40));
 44         userRepository.save(new User(3L, "kaka", 50));
 45         userRepository.save(new User(4L, "didi2", 30));
 46         userRepository.save(new User(5L, "mama", 40));
 47         userRepository.save(new User(6L, "kaka2", 50));
 48         userRepository.save(new User(7L, "kaka", 50));
 49         userRepository.save(new User(8L, "kao", 50));
 50         userRepository.save(new User(9L, "ekakae", 50));
 51         userRepository.save(new User(10L, "kaka5", 50));
 52         userRepository.save(new User(11L, "", 50));
 53         userRepository.save(new User(12L, null, 50));
 54         this.logger.info(String.valueOf(userRepository.findAll().size()));
 55 
 56         // 删除一个User,再验证User总数
 57         /*User u = userRepository.findOne(1L);
 58         this.logger.info(u.toString());
 59         userRepository.delete(u);
 60         this.logger.info(String.valueOf(userRepository.findAll().size()));
 61 
 62         // 删除一个User,再验证User总数
 63         u = userRepository.findByUsername("mama").get(0);
 64         this.logger.info(u.toString());
 65         userRepository.delete(u);
 66         this.logger.info(String.valueOf(userRepository.findAll().size()));*/
 67 
 68     }
 69 
 70     @Test
 71     public void test2() throws Exception {
 72 
 73         // 删除一个User,再验证User总数
 74         List<User> u1 = userRepository.findByUsernameLike("kaka");
 75         this.logger.info(u1.toString());
 76         List<User> u2 = userRepository.findByUsername("mama");
 77         this.logger.info(u2.toString());
 78         List<User> u3 = userRepository.findByAgeGreaterThan(40);
 79         this.logger.info(u3.toString());
 80         List<User> u4 = userRepository.findByAgeLessThan(40);
 81         this.logger.info(u4.toString());
 82         List<User> u5 = userRepository.findByAgeBetween(30,45);
 83         this.logger.info(u5.toString());
 84         List<User> u6 = userRepository.findByUsernameNotNull();
 85         this.logger.info(u6.toString());
 86         List<User> u7 = userRepository.findByUsernameNull();
 87         this.logger.info(u7.toString());
 88         List<User> u8 = userRepository.findByUsernameNot("kaka");
 89         this.logger.info(u8.toString());
 90 
 91 
 92 
 93 
 94     }
 95 
 96     @Test
 97     public void test3() throws Exception {
 98 
 99         Pageable pageable = new PageRequest(0,10);
100         Page<User> u1 = userRepository.findByNameAndAgeRange("kaka",50,pageable);
101         this.logger.info(u1.toString());
102         Page<User> u2 = userRepository.findByNameAndAgeRange2("kaka",0,50,pageable);
103         this.logger.info(u2.toString());
104         Page<User> u3 = userRepository.findByNameAndAgeRange3("kaka",0,50,pageable);
105         this.logger.info(u3.toString());
106 
107     }
108 }
View Code

9.GITHUB地址

https://github.com/nbfujx/springBoot-learn-demo/tree/master/spring-boot-mongodb