1. 程式人生 > >spring-boot整合mongodb的案例

spring-boot整合mongodb的案例

 

1.簡介

MongoDB 是一個基於分散式檔案儲存的資料庫。由 C++ 語言編寫。旨在為 WEB 應用提供可擴充套件的高效能資料儲存解決方案。

MongoDB 是一個介於關係資料庫和非關係資料庫之間的產品,是非關係資料庫當中功能最豐富,最像關係資料庫的。

2.執行環境

開發工具:intellij idea

JDK版本:1.8

專案管理工具:Maven 4.0.0

3.Maven Plugin管理

複製程式碼

 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>

複製程式碼

4.application.properties編寫

1 spring.data.mongodb.uri= mongodb://localhost:27017/goku_db1

5.DemoApplication啟動類編寫

複製程式碼

 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 }

複製程式碼

6.User編寫

複製程式碼

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+"\"}\"";
    }
}

複製程式碼

7.UserRepository編寫

與HibernateRepository類似,通過繼承MongoRepository介面,我們可以非常方便地實現對一個物件的增刪改查,要使用Repository的功能,先繼承MongoRepository<T, TD>介面,其中T為倉庫儲存的bean類,TD為該bean的唯一標識的型別,一般為ObjectId。之後在service中注入該介面就可以使用,無需實現裡面的方法,spring會根據定義的規則自動生成。

但是MongoRepository實現了的只是最基本的增刪改查的功能,要想增加額外的查詢方法,可以按照以下規則定義介面的方法。自定義查詢方法,格式為“findBy+欄位名+方法字尾”,方法傳進的引數即欄位的值,此外還支援分頁查詢,通過傳進一個Pageable物件,返回Page集合。

下面是支援的查詢型別,每三條資料分別對應:(方法字尾,方法例子,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 }

複製程式碼

儘管以上查詢功能已經很豐富,但如果還不能滿足使用情況的話可以用一下方法---基於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);

複製程式碼

8.UserRepositoryTest測試編寫

複製程式碼

  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 }

複製程式碼

9.GITHUB地址

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